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();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
相关文章
相关标签/搜索