1.map中有null key時的序列化
當有null key時,jackson序列化會報 Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)
處理此異常有兩種方式
- 1.需要自定義一個序列化null key的方法
- 2. map中直接remove null key
這里只討論第一種:
處理方法為 mapper.getSerializerProvider().setNullKeySerializer(new NullKeySerializer()); 將null key處理為空字符
@Test public void testSerializMapNullKey() throws JsonProcessingException { //ignore map null value Map<String, Object> map = new HashMap<>(); map.put(null, "test"); ObjectMapper mapper = new ObjectMapper(); mapper.getSerializerProvider().setNullKeySerializer(new NullKeySerializer()); System.out.println(mapper.writeValueAsString(map)); } static class NullKeySerializer extends StdSerializer<Object> { public NullKeySerializer() { this(null); } public NullKeySerializer(Class<Object> t) { super(t); } @Override public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName(""); } }
{"":"test"} Process finished with exit code 0
2. 處理null value的情況
@Test public void testIgnoreMapNullValue() throws JsonProcessingException { //ignore null key Map<String, Object> map = new HashMap<>(); map.put("key", "test"); map.put("key1", null); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); System.out.println(mapper.writeValueAsString(map)); }
輸出為:{"key":"test"} 並沒有 key1:null
{"key":"test"} Process finished with exit code 0
3. 處理實體中filed中值為null的情況
使用注解:@JsonInclude(JsonInclude.Include.NON_NULL)
注意:@JsonInclude(JsonInclude.Include.NON_NULL)即可以在實體上用,也可以在filed中使用,比如在name上用這個注解
@Test public void testIgnoreNullFiled() throws JsonProcessingException { //test ignore null filed User user = new User(); user.setName(null); user.setHouse("asdf"); ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(user)); } /** * ignore null filed */ @JsonInclude(JsonInclude.Include.NON_NULL) class User { private String name; private String house; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHouse() { return house; } public void setHouse(String house) { this.house = house; } }
輸出為:
{"house":"asdf"} Process finished with exit code 0
如果設置全局怎么設置呢,使用: mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
@Test public void testIgnoreNullFiledGlobally() throws JsonProcessingException { //test ignore null filed User user = new User(); user.setName(null); user.setHouse("asdf"); ObjectMapper mapper = new ObjectMapper(); //Ignore Null Fields Globally mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); System.out.println(mapper.writeValueAsString(user)); }
參考:1.https://www.baeldung.com/jackson-map-null-values-or-null-key
2.https://github.com/eugenp/tutorials/tree/master/jackson-simple