简体   繁体   中英

How to deserialize json with optional fields using Gson

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.

尝试下面的Gson实例

Gson gson = new GsonBuilder().serializeNulls().create();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM