Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON JsonElement to String

Tags:

java

json

gson

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();
like image 489
tallaghi Avatar asked Jul 20 '15 16:07

tallaghi


People also ask

What is JsonElement in GSON?

A class representing an element of Json. It could either be a JsonObject , a JsonArray , a JsonPrimitive or a JsonNull .

How do I convert a JSON object to a string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

Is JsonParser deprecated?

Deprecated. No need to instantiate this class, use the static methods instead.

What is the use of JsonParser in Java?

Interface JsonParser. Provides forward, read-only access to JSON data in a streaming way. This is the most efficient way for reading JSON data. The class Json contains methods to create parsers from input sources ( InputStream and Reader ).


Video Answer


1 Answers

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

do check first:

item.get("start").isJsonNull() ? "" : item.get("start").getAsString();
like image 184
Алексей Avatar answered Sep 29 '22 00:09

Алексей