Jackson 转换JSON,SpringMVC ajax 输出,当值为null或者空不输出字段@JsonInclude

当我们提供接口的时候,  Ajax  返回的时候,当对象在转换  JSON  (序列化)的时候,值为Null 或者为“”的字段还是输出来了。看上去不优雅。

现在我叙述三种方式来控制这种情况。

注解的方式( @JsonInclude(JsonInclude.Include.NON_EMPTY))

通过@JsonInclude 注解来标记,但是值的可选项有四类。

  1. Include.Include.ALWAYS (Default / 都参与序列化) 
  2. Include.NON_DEFAULT(当Value 为默认值的时候不参与,如Int a; 当 a=0 的时候不参与)
  3. Include.NON_EMPTY(当Value 为“” 或者null 不输出)
  4. Include.NON_NULL(当Value 为null 不输出)

注解使用如下:

 
  1. ... ...
  2.  
  3. //如果是null 和 “” 不返回
  4. @JsonInclude(JsonInclude.Include.NON_EMPTY)
  5. private T data;
  6.  
  7. ... ...

我的对象定义(其实就是一个API接口的返回对象):

 
  1. public class APIResult<T> implements Serializable {
  2. //状态
  3. private Integer status;
  4. //描述
  5. private String message;
  6.  
  7. //如果是null 不返回
  8. @JsonInclude(JsonInclude.Include.NON_EMPTY)
  9. private T data;
  10. /*** getter / setter***/
  11. }

我的前端返回值:

 
  1. {"status":200,"message":"success"}

如上,基本达到我的要求了。

代码方式:

 
  1. ObjectMapper mapper = new ObjectMapper();
  2. //null不序列化
  3. mapper.setSerializationInclusion(Include.NON_NULL);
  4.  
  5. Demo demo = new Demo(200,"",null);
  6. String json = mapper.writeValueAsString(demo);
  7. System.out.println(json);
  8. //结果:{"st":200,"name":""} 为null的属性没输出。

Spring配置文件实现

当我们整个项目都需要某一种规则的时候,那么我们就采用配置文件配置。

先还是上一下  Jackson  的  Maven  配置:

 
  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-core</artifactId>
  4. <version>${jackson.version}</version>
  5. </dependency>
  6.  
  7. <dependency>
  8. <groupId>com.fasterxml.jackson.core</groupId>
  9. <artifactId>jackson-databind</artifactId>
  10. <version>${jackson.version}</version>
  11. </dependency>

再来一个XML配置:

 
  1. <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
  2. <property name="serializationInclusion">
  3. <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
  4. </property>
  5. </bean>
  6. <mvc:annotation-driven>
  7. <mvc:message-converters>
  8. <bean
  9. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
  10. <property name="objectMapper" ref="objectMapper" />
  11. </bean>
  12. </mvc:message-converters>
  13. </mvc:annotation-driven>

其实所有的姿势都是针对  Jackson  提供给我们的入口“JsonInclude.Include” 来处理的。所以只要记住最上面讲的几个级别就可以了。

猜你喜欢

转载自blog.csdn.net/fygkchina/article/details/84953868
今日推荐