How to deserialize json with optional fields using Gson
gson, java, json
Solution
Try below Gson instance
Gson gson = new GsonBuilder().serializeNulls().create();
Problem
I'm using Gson to deserialize a JSON string from a given API using the following Code. ``` Gson gson = new Gson(); Map<String, CustomDto> test = gson.fromJson(result, new TypeToken<Map<String, CustomDto>>() {}.getType()); ``` The `CustomDto` is an object constructed from primitives (int, long, boolean) and another Object. The problem I run into is that this Object is optional. Sometimes it gets transmitted, sometimes it is just not there. I was expecting if a field is missing in the JSON string that the associated set method should not be called (like in Jackson) and it should just work unfortunate that is not the case and i run into an exception: ``` Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 207 column 23 ``` If I remove the field from the `CustomDto`, it just works fine but then there is the problem if it will get transmitted. May I ask is there some annotation to flag fields optional in the entity class or can someone give me some advice how to handle this? Thanks everyone.