Java

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

2020-03-13  本文已影响0人  ProjectDaedalus

后端返回给前端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

上一篇下一篇

猜你喜欢

热点阅读