很多人在把一个对象转成json得,并不希望把key对应的value为null的这个key出现在json中,我自己正好有这个需求,查看api发现,有很多可配置的序列化参数,各位可以根据需要配置想要的参数值,实例如下
结果:
public static void main(String[] args) {
Map map = new HashMap();
map.put("test", null) ;
map.put("1", 1) ;
String jsonstr = null ;
ObjectMapper om = new ObjectMapper(new JsonFactory());
try {
om.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); //配置不写value为null的key
jsonstr = om.writeValueAsString(map);
} catch (Exception e) {
log.warn("to json string exception, will use fastjson to parse", e);
}
System.out.println(jsonstr);
}
结果:
{"1":1}