tallaghi
tallaghi

Reputation: 345

GSON JsonElement to String

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.

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();

Upvotes: 16

Views: 45270

Answers (2)

Алексей
Алексей

Reputation: 1847

Is it possible that item.get("start") is a JsonNull?

do check first:

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

Upvotes: 19

K.AJ
K.AJ

Reputation: 1292

I found Gson to be very straight forward and useful for marshal and unmarshal an object into 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);
}

Upvotes: 0

Related Questions