如何使用Gson反序列化带有可选字段的json [英] How to deserialize json with optional fields using Gson

查看:282
本文介绍了如何使用Gson反序列化带有可选字段的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Gson从给定的API中反序列化JSON字符串,使用下面的代码。

  Gson gson = new GSON(); 
地图< String,CustomDto> test = gson.fromJson(result,new TypeToken< Map< String,CustomDto>>(){} .getType());

CustomDto 是一个由基元构造的对象(int,long,boolean)和另一个Object。我碰到的问题是这个对象是可选的。有时候会传播,有时它不会。我期待如果JSON字符串中缺少一个字段,而不应该调用相关的set方法(就像在Jackson中一样),并且它应该工作不幸,但情况并非如此,我遇到了一个异常:

 线程main中的异常com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期的BEGIN_ARRAY,但在第207行第23列处为STRING 

如果我从 CustomDto 中删除​​该字段,只是工作正常,但如果它会得到传输是有问题的。请问是否有一些注解在实体类中标记字段可选,或者有人可以给我一些建议如何处理?

感谢所有人。

解决方案

下面试试Gson实例

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


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.

解决方案

Try below Gson instance

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

这篇关于如何使用Gson反序列化带有可选字段的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆