Java Gson 忽略 value=null 的映射条目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3923759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Gson ignoring map entries with value=null
提问by m2o
Gson gson = new Gson();
Map<String,Object> map = new HashMap<String, Object>();
map.put("a", 1);
map.put("b", null);
System.out.println(gson.toJson(map)); //prints {"a":1}
How do I get it to include all entries?
如何让它包含所有条目?
采纳答案by Alois Cochard
See Gson User Guide - Null Object Support:
The default behaviour that is implemented in Gson is that null object fields are ignored. This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java form.
Here's how you would configure a Gson instance to output null:
Gson gson = new GsonBuilder().serializeNulls().create();
Gson 中实现的默认行为是忽略空对象字段。这允许更紧凑的输出格式;但是,当 JSON 格式转换回其 Java 格式时,客户端必须为这些字段定义默认值。
以下是配置 Gson 实例以输出 null 的方法:
Gson gson = new GsonBuilder().serializeNulls().create();