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();spa
mapper.setSerializationInclusion(Include.NON_NULL); code
//經過該方法對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);對象
注意:只對VO起做用,Map List不起做用blog
例如ci
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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
|
1
2
3
4
5
6
7
8
9
10
11
|
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());<br>
輸出
{
"b"
:
"b"
}
|b
|