【发布时间】:2011-04-24 20:06:19
【问题描述】:
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}
如何让它包含所有条目?
【问题讨论】:
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}
如何让它包含所有条目?
【问题讨论】:
见Gson User Guide - Null Object Support:
在 Gson 中实现的默认行为是忽略空对象字段。这允许更紧凑的输出格式;但是,客户端必须为这些字段定义默认值,因为 JSON 格式会转换回其 Java 格式。
以下是配置 Gson 实例以输出 null 的方式:
Gson gson = new GsonBuilder().serializeNulls().create();
【讨论】: