美文网首页Java
JSON处理(三): 不返回null字段 @JsonInclud

JSON处理(三): 不返回null字段 @JsonInclud

作者: ProjectDaedalus | 来源:发表于2020-03-13 11:21 被阅读0次

    后端返回给前端JSON格式的对象数据中,当对象的字段为NULL时,该字段也会写入JSON返回;而很多时候前端期望后端只返回对象中非null的字段数据。在Jackson框架中提供了 @JsonInclude 注解以实现该功能

    abstract.png

    不返回null字段数据

    在相关对象的类上添加 @JsonInclude 注解,设定值为 NON_NULL

        @JsonInclude(JsonInclude.Include.NON_NULL)
        public class Student
        {
            private int id;
            private String username;
            private String sex;
            private String address;
            ...
        }
    

    则HTTP Response返回的该类的对象的JSON数据如下所示,无为null的字段

        {
            "id": 0,
            "username": "Kallen",
            "sex": "female"
        }
    

    返回null字段数据

    在相关对象的类上添加 @JsonInclude 注解,设定值为 ALWAYS

        @JsonInclude(JsonInclude.Include.ALWAYS)
    

    则HTTP Response返回的该类的对象的JSON数据如下所示,其中包含null的字段

        {
            "id": 0,
            "username": "Kallen",
            "sex": "female",
            "address": null
        }
    

    Note

    • 该注解不设定值的情况下,默认使用 ALWAYS

    相关文章

      网友评论

        本文标题:JSON处理(三): 不返回null字段 @JsonInclud

        本文链接:https://www.haomeiwen.com/subject/lirqshtx.html