jackson 實體轉json 爲NULL或者爲空不參加序列化

1.實體上java

@JsonInclude(Include.NON_NULL) app

//將該標記放在屬性上,若是該屬性爲NULL則不參與序列化
//若是放在類上邊,那對這個類的所有屬性起做用
//Include.Include.ALWAYS 默認
//Include.NON_DEFAULT 屬性爲默認值不序列化
//Include.NON_EMPTY 屬性爲 空(「」) 或者爲 NULL 都不序列化
//Include.NON_NULL 屬性爲NULL 不序列化


2.代碼上
ObjectMapper mapper = new ObjectMapper();對象

mapper.setSerializationInclusion(Include.NON_NULL);  blog

//經過該方法對mapper對象進行設置,全部序列化的對象都將按改規則進行系列化
//Include.Include.ALWAYS 默認
//Include.NON_DEFAULT 屬性爲默認值不序列化
//Include.NON_EMPTY 屬性爲 空(「」) 或者爲 NULL 都不序列化
//Include.NON_NULL 屬性爲NULL 不序列化

User user = new User(1,"",null);
String outJson = mapper.writeValueAsString(user);
System.out.println(outJson);
get

 

注意:只對VO起做用,Map List不起做用it

例如io

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);

Map map = new HashMap();
map.put("a", null);
map.put("b", "b");

String ret_val = mapper.writeValueAsString(map);
System.err.println(ret_val);
Map m = mapper.readValue(ret_val, Map.class);
System.err.println(m.get("a") + "|" + m.get("b"));
輸出:
{"b":"b","a":null}
null|b

  

VO vo = new VO();
vo.setA(null);
vo.setB("b");
		
String ret_val1 = mapper.writeValueAsString(vo);
System.err.println(ret_val1);
VO v = mapper.readValue(ret_val1, VO.class);
System.err.println(v.getA() + "|" + v.getB());
輸出
{"b":"b"}
|b
相關文章
相關標籤/搜索