Java GSON JsonElement 转字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31521652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
GSON JsonElement to String
提问by tallaghi
I am having some trouble converting an JsonElement to string. I am using the getAsString() method call but i keep getting an Unsupported Operation Exception. I checked the output of the get I am calling and it seems correct.
我在将 JsonElement 转换为字符串时遇到了一些问题。我正在使用 getAsString() 方法调用,但我不断收到不受支持的操作异常。我检查了我正在调用的 get 的输出,它似乎是正确的。
Here is my code, Sorry for the poor naming conventions:
这是我的代码,抱歉糟糕的命名约定:
JsonParser jp2 = new JsonParser();
JsonObject root2 = jp2.parse(getAllEventsResults.get_Response()).getAsJsonObject();
JsonArray items2 = root2.get("items").getAsJsonArray();
for(int i=0; i<items2.size(); i++){
JsonObject item = items2.get(i).getAsJsonObject();
System.out.println(item.get("start").getAsString());}
The weirdest part of this is that I do the same exact thing in above with this code:
最奇怪的部分是我用这段代码在上面做同样的事情:
JsonParser jp = new JsonParser();
JsonObject root = jp.parse(getAllCalendarsResults.get_Response()).getAsJsonObject();
JsonArray items = root.get("items").getAsJsonArray();
JsonObject firstItem = items.get(0).getAsJsonObject();
String firstCalId = firstItem.get("id").getAsString();
采纳答案by Алексей
Is it possible that item.get("start")
is a JsonNull
?
有可能item.get("start")
是一个JsonNull
吗?
do check first:
首先检查:
item.get("start").isJsonNull() ? "" : item.get("start").getAsString();
回答by K.AJ
I found Gson to be very straight forward and useful for marshal and unmarshal an object into json and vice versa.
我发现 Gson 非常直接,对于将对象编组和解组为 json 非常有用,反之亦然。
It was as simple as two helper methods..
它就像两个辅助方法一样简单..
/**
* Converts an object to a Json String
*
* @param obj - The object to convert to Json
* @param dfString - data format pattern.
* @return
*/
public static String toJson(Object obj, String dfString) {
Gson gson = new GsonBuilder().setDateFormat(dfString).create();
return gson.toJson(obj);
}
/**
* Converts a Json String to the specified Class<T>
*
* @param json - The Json String to covert to Class<T> instance
* @param obj - The Class<T> representation of the Json String
* @return
*/
public static <T> T fromJson(String json, Class<T> obj, String dfString) {
Gson gson = new GsonBuilder().setDateFormat(dfString).create();
return gson.fromJson(json, obj);
}