How do I write a custom JSON deserializer for Gson?

I’d take a slightly different approach as follows, so as to minimize “manual” parsing in my code, as unnecessarily doing otherwise somewhat defeats the purpose of why I’d use an API like Gson in the first place. // output: // [User: id=1, name=Jonas, updateDate=2011-03-24 03:35:00.226] // [User: id=5, name=Test, updateDate=2011-05-07 08:31:38.024] // using java.sql.Timestamp public … Read more

Deserialize a List object with Gson?

Method to deserialize generic collection: import java.lang.reflect.Type; import com.google.gson.reflect.TypeToken; … Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType(); List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType); Since several people in the comments have mentioned it, here’s an explanation of how the TypeToken class is being used. The construction new TypeToken<…>() {}.getType() captures a compile-time type (between the < and >) … Read more

JSON parsing using Gson for Java

This is simple code to do it, I avoided all checks but this is the main idea. public String parse(String jsonLine) { JsonElement jelement = new JsonParser().parse(jsonLine); JsonObject jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonObject(“data”); JsonArray jarray = jobject.getAsJsonArray(“translations”); jobject = jarray.get(0).getAsJsonObject(); String result = jobject.get(“translatedText”).getAsString(); return result; } To make the use more generic – … Read more

Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?

As the exception message states Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 16 path $.nestedPojo while deserializing, Gson was expecting a JSON object, but found a JSON array. Since it couldn’t convert from one to the other, it threw this exception. The JSON format is described here. In short, it … Read more