Essej
Essej

Reputation: 861

Gson getAsString() fails if json array is empty

I'm using the Json library Gson in Java to parse json strings into CSV files. Some of my json fields are null so I will have to check for that and add an empty string instead. Some of the fields in my json strings are arrays and some of them are empty. However, when these arrays are empty, the getAsString method in Gson fails with illeagStateException. Here is a runnable example:

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

JsonObject message = new JsonParser().parse("{\"id\":null,\"text\":\"test\",\"types\":[]}").getAsJsonObject();
JsonElement element = message.get("types"); //now this is "[]"
String jsonElementAsString= element.isJsonNull() ? "" : element.getAsString(); //Here exception is thrown.

I'm already checking if json is null. What is a good workaround here? I would like to avoid adding to much clutter in order to improve execution time. I could of course wrap it all in a try catch but that is expensive.

Upvotes: 2

Views: 1837

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40078

Since we know types is an Array, the best way i would do is, first check types is existed in JsonObject

if(message.has("types"))  //which avoids null pointer exception

Then get the types as JsonArray

JsonArray typesArray = message.getAsJsonArray("types");

And then use forEach so you don't need to care if array is empty also

typesArray.forEach(element->System.out.println(element));

Upvotes: 4

Related Questions