GSON JsonElement for string

I'm having problems converting JsonElement to string. I am using the getAsString () method call, but I keep getting an exception from the improper operation. I checked the get output that I am calling and it seems correct.

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 am doing the same thing in the above code 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();
+4
source share
2 answers

Could it be that item.get("start")is JsonNull?

check first:

item.get("start").isJsonNull() ? "" : item.get("start").getAsString();
+7
source

I found that Gsson is very straightforward and useful for the marshal, and also dismounts the object in json and vice versa.

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);
}
+2
source

Source: https://habr.com/ru/post/1598735/


All Articles