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


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

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

    注解的方式( @JsonInclude(JsonInclude.Include.NON_EMPTY))
    通过@JsonInclude 注解来标记,但是值的可选项有四类。
    Include.Include.ALWAYS (Default / 都参与序列化)
    Include.NON_DEFAULT(当Value 为默认值的时候不参与,如Int a; 当 a=0 的时候不参与)
    Include.NON_EMPTY(当Value 为“” 或者null 不输出)
    Include.NON_NULL(当Value 为null 不输出)

    注解使用如下:

    //如果是null 和 “” 不返回
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private T data;

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

    public class APIResult<T> implements Serializable {
        //状态
        private Integer status;
        //描述
        private String message;
        //如果是null 不返回
        @JsonInclude(JsonInclude.Include.NON_EMPTY)
        private T data;
        /*** getter / setter***/
    }

    我的前端返回值:

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

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

    代码方式:

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

    Spring配置文件实现

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

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

    <dependency>  
        <groupId>com.fasterxml.jackson.core</groupId>  
        <artifactId>jackson-core</artifactId>  
        <version>${jackson.version}</version>  
    </dependency>  
      
    <dependency>  
        <groupId>com.fasterxml.jackson.core</groupId>  
        <artifactId>jackson-databind</artifactId>  
        <version>${jackson.version}</version>  
    </dependency> 

    再来一个XML配置:

    <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">   
        <property name="serializationInclusion">  
            <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>  
        </property>  
    </bean>
    <mvc:annotation-driven>  
        <mvc:message-converters>  
            <bean  
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
                <property name="objectMapper" ref="objectMapper" />  
            </bean>  
        </mvc:message-converters>  
    </mvc:annotation-driven>

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

    其实这些都是一些基础知识,我只是整合下,后面要丰富首页的内容。

  • 相关阅读:
    软件工程作业3.28
    毕业论文管理系统建模图
    软件工程建模图作业
    酒店管理系统
    闪屏和功能引导页面代码编写
    Android算法编程代码
    3.28软件工程作业
    毕业论文管理系统
    图书管理系统建模图
    酒店预订系统故事
  • 原文地址:https://www.cnblogs.com/winner-0715/p/8057832.html
Copyright © 2020-2023  润新知