一直比较担心基本类型的值如果其对应的json字符串中定义的是null类型,Gson解析会不会报错?
比如定义下面的类型:
public class DataBean {
public int id;
}
其对应的json字符串为{"id": null}
的情况,使用Gson进行反序列化操作是否会报错?
String dataStr = "{\"id\": null}";
DataBean parsed = new Gson().fromJson(dataStr, DataBean.class);
实际以上代码并不会抛出异常,最终得到的parsed
变量其内部属性id
值为0。OK,心安了。
如果你定义的id
为Integer
这种包装类型,则解析后的值为null
。另外,在进行序列化的时候,如果某个字段的值为null
,则Gson不会将其序列化到字符串中。
以上,同理应该可以推及到其他基本类型,比如float
和double
等。
备注:以上测试使用的Gson版本为2.8.5