gee*_*eks 8 java json jackson gson
我已经开始使用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 ****************************");
Run Code Online (Sandbox Code Playgroud)
生成这个:
{"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 ****************************");
Run Code Online (Sandbox Code Playgroud)
它生成了这个(这就是我想要的 - 请注意,"urlList":null未生成):
{"eatwithrustyspoon":{"device":"iPad","os":"iPhone OS","peer_id"
Bri*_*ach 12
我可以省略使用null值编写Bean属性吗?("如何防止写入null属性","如何抑制空值")
是.根据JacksonAnnotationSerializeNulls,您可以使用:
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
// or (for older versions):
objectMapper.configure(SerializationConfig.WRITE_NULL_PROPERTIES, false);
Run Code Online (Sandbox Code Playgroud)
瞧,没有更多的空值.请注意,您必须在bean序列化之前配置映射器,因为此设置可能与序列化程序一起缓存.因此设置得太晚可能会阻止更改生效.
归档时间: |
|
查看次数: |
14007 次 |
最近记录: |