我已经开始使用Jackson作为JSON生成器,作为谷歌GSON的替代品。我遇到了Jackson生成对象的问题:如果对象确实为null,则为null。另一方面,GSON在JSON中生成NO条目,这是我想要的行为。有没有办法阻止杰克逊在对象丢失时生成空对象/值?
杰克逊
ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
mapper.writeValue(sw, some_complex_object);
String jackson = sw.getBuffer().toString();
System.out.println("********************* START JACKSON JSON ****************************");
System.out.println(jackson);
System.out.println("********************* END JACKSON JSON ****************************");
生成这个:
{“eatwithrustyspoon”:{“urlList”:null ,“device”:“iPad”,“os”:“iPhone OS”,“peer_id”:
和GSON看起来像这样:
Gson gson = new Gson();
String json = gson.toJson(some_complex_object);
System.out.println("********************* START GSON JSON ****************************");
System.out.println(json);
System.out.println("********************* END GSON JSON ****************************");
它生成了这个(这就是我想要的 - 请注意,“urlList”:null未生成):
{“eatwithrustyspoon”:{“device”:“iPad”,“os”:“iPhone OS”,“peer_id”
答案 0 :(得分:12)
我可以省略使用null值编写Bean属性吗? (“如何防止写入null属性”,“如何抑制空值”)
是。根据{{3}},您可以使用:
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
// or (for older versions):
objectMapper.configure(SerializationConfig.WRITE_NULL_PROPERTIES, false);
并且瞧,没有更多的空值。请注意,您必须在bean序列化之前配置映射器,因为此设置可能与序列化程序一起缓存。因此设置得太晚可能会阻止变更生效。
答案 1 :(得分:2)
我的问题有点不同,实际上我得到了POJO类属性的Null值。
然而我通过给我的pojo类中的属性映射解决了这个问题:
@JsonProperty(" PROPERTY_NAME&#34)
认为它可以帮助某人:)
答案 2 :(得分:1)
以下解决方案救了我。
objectMapper.setSerializationInclusion(Include.NON_NULL);