jackSon注解– @JsonInclude 注解不返回null值字段

本文深入探讨了Jackson JSON框架中的注解使用,包括@JsonIgnore、@JsonIgnoreProperties、@JsonIgnoreType、@JsonProperty、@JsonPropertyOrder、@JsonInclude和@JsonSetter等,讲解了它们在序列化和反序列化过程中的应用。
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class OrderDTO {

    private String orderId;
    @JsonProperty("name")
    private String buyerName;
    @JsonProperty("phone")
    private String buyerPhone;
    @JsonProperty("address")
    private String buyerAddress;
    @JsonProperty("openid")
    private String buyerOpenid;
    private BigDecimal orderAmount;

    /**
     * 订单状态,默认是0
     */
    private Integer orderStatus;

    /**
     * 支付状态
     */
    private Integer payStatus;

    @JsonSerialize(using = Date2LongSerializer.class)
    private Timestamp createTime;
    @JsonSerialize(using = Date2LongSerializer.class)
    private Timestamp updateTime;

    @JsonProperty("items")
    List<OrderDetailEntity> orderDetailList;


}
复制代码

@JsonInclude(JsonInclude.Include.NON_NULL)表示,如果值为null,则不返回

全局jsckson配置

复制代码
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://192.168.41.60/sell?characterEncoding=utf-8&useSSL=false
  jpa:
    show-sql: true
  jackson:
    default-property-inclusion: non_null # 全局jackson配置
复制代码

JSON库 Jackson 常用注解介绍

Jackson JSON 框架中包含了大量的注解来让我们可以干预 Jackson 的 JSON 处理过程,
例如我们可以通过注解指定 java pojo 的某些属性在生成 json 时被忽略。。本文主要介绍如何使用 Jackson 提供的注解。
Jackson注解主要分成三类,一是只在序列化时生效的注解;二是只在反序列化时候生效的注解;三是两种情况下都生效的注解。

一: 两种情况下都有效的注解

1. @JsonIgnore 作用域属性或方法上

@JsonIgnore 用来告诉 Jackson 在处理时忽略该注解标注的 java pojo 属性,
不管是将 java 对象转换成 json 字符串,还是将 json 字符串转换成 java 对象。

复制代码
@Data
public class SellerInfoEntity {

    private String id;
    private String username;
    private String password;
    private String openid;

    @JsonIgnore
    private Timestamp createTime;
    @JsonIgnore
    private Timestamp updateTime;


    public SellerInfoEntity() {
    }

    public SellerInfoEntity(String id, String username, String password, String openid) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.openid = openid;
    }
}
复制代码

2. @JsonIgnoreProperties 作用在类上

@JsonIgnoreProperties 和 @JsonIgnore 的作用相同,都是告诉 Jackson 该忽略哪些属性,
不同之处是 @JsonIgnoreProperties 是类级别的,并且可以同时指定多个属性。

复制代码
@Data
@JsonIgnoreProperties(value = {"createTime","updateTime"})
public class SellerInfoEntity {

    private String id;
    private String username;
    private String password;
    private String openid;

    private Timestamp createTime;
    private Timestamp updateTime;


    public SellerInfoEntity() {
    }

    public SellerInfoEntity(String id, String username, String password, String openid) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.openid = openid;
    }
}
复制代码

使用Spring Boot快速搭建Controller进行测试:

复制代码
@RestController
@RequestMapping("/jackson")
public class TestJackson {
    @RequestMapping("test1")
    public Result test1(){

        SellerInfoEntity entity = new SellerInfoEntity("1","user1","123456","openid");

        return new Result(MyResultEnum.SUCCESS,entity);

    }
}
复制代码

访问: localhost/sell/jackson/test1

使用注解前:返回值

复制代码
{
    "code": 0,
    "msg": "成功",
    "data": {
        "id": "1",
        "username": "user1",
        "password": "123456",
        "openid": "openid",
        "createTime": null,
        "updateTime": null
    }
}
复制代码

使用注解后:返回值

复制代码
{
    "code": 0,
    "msg": "成功",
    "data": {
        "id": "1",
        "username": "user1",
        "password": "123456",
        "openid": "openid",
    }
}
复制代码

3. @JsonIgnoreType

@JsonIgnoreType 标注在类上,当其他类有该类作为属性时,该属性将被忽略。

复制代码
package org.lifw.jackosn.annotation;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
@JsonIgnoreType
public class SomeOtherEntity {
    private Long id;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
}
复制代码
public class SomeEntity {
    private String name;
    private String desc;
    private SomeOtherEntity entity;
}

SomeEntity 中的 entity 属性在json处理时会被忽略。

4. @JsonProperty

@JsonProperty 可以指定某个属性和json映射的名称。例如我们有个json字符串为{“user_name”:”aaa”},
而java中命名要遵循驼峰规则,则为userName,这时通过@JsonProperty 注解来指定两者的映射规则即可。这个注解也比较常用。

public class SomeEntity {
    @JsonProperty("user_name")
    private String userName;
      // ...
}

二、只在序列化情况下生效的注解

1. @JsonPropertyOrder

在将 java pojo 对象序列化成为 json 字符串时,使用 @JsonPropertyOrder 可以指定属性在 json 字符串中的顺序。

2. @JsonInclude

在将 java pojo 对象序列化成为 json 字符串时,使用 @JsonInclude 注解可以控制在哪些情况下才将被注解的属性转换成 json,例如只有属性不为 null 时。

复制代码
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SellerInfoEntity {

    private String id;
    private String username;

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private String password;
    private String openid;

    private Timestamp createTime;
    private Timestamp updateTime;


    public SellerInfoEntity() {
    }

    public SellerInfoEntity(String id, String username, String password, String openid) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.openid = openid;
    }
}
复制代码

Controller 测试

复制代码
@RestController
@RequestMapping("/jackson")
public class TestJackson {

    @RequestMapping("test1")
    public Result test1(){

        SellerInfoEntity entity = new SellerInfoEntity("1","user1","","openid");

        return new Result(MyResultEnum.SUCCESS,entity);
    }
}
复制代码

结果:

复制代码
{
    "code": 0,
    "msg": "成功",
    "data": {
        "id": "1",
        "username": "user1",
        "openid": "openid"
    }
}
复制代码

上述例子的意思是 SellerInfoEntity 的所有属性只有在不为 null 的时候才被转换成 json,
如果为 null 就被忽略。并且如果password为空字符串也不会被转换.

该注解也可以加在某个字段上。

另外还有很多其它的范围,例如 NON_EMPTY、NON_DEFAULT等

三、是在反序列化情况下生效的注解

1. @JsonSetter

@JsonSetter 标注于 setter 方法上,类似 @JsonProperty ,也可以解决 json 键名称和 java pojo 字段名称不匹配的问题。

复制代码
public class SomeEntity {
    private String desc;
    @JsonSetter("description")
    public void setDesc(String desc) {
        this.desc = desc;
    }
}
复制代码

上述例子中在将 json 字符串转换成 SomeEntity 实例时,会将 json 字符串中的 description 字段赋值给 SomeEntity 的 desc 属性。

转载于:https://www.cnblogs.com/xinglongbing521/p/10319419.html

### @JsonInclude 注解的详细用法 #### 一、引言 在现代Web应用程序中,JSON作为一种轻量级的数据交换格式,被广泛用于前后端之间的数据传输。为了更好地控制对象到JSON字符串以及反之的过程,Jackson库提供了一系列注解[@^3]。 #### 二、@JsonInclude 注解概述 `@JsonInclude` 是 Jackson 提供的一个重要注解,主要用于指定如何处理那些可能为或具有默认的对象属性,在序列化过程中决定是否忽略这些字段【^4】。此注解可以应用于类级别或者方法/字段级别,并接受同的策略选项来定制行为【^1】。 #### 参数介绍 该注解支持多种枚举类型的参数设置,最常用的有: - `NON_NULL`: 只当字段null 时才包含; - `NON_ABSENT`: 对于 Optional 类型来说只有存在实际才会加入 JSON 结果里; - `NON_DEFAULT`: 排除基本类型采用其零(如 int=0, boolean=false),对于 String 则是非白串之外的情况都将保留; - `ALWAYS`: 总是写出所有声明过的成员变量,论它们是否有赋过新得情况发生; 特别提到的是 `NON_EMPTY`, 它仅会排除null还会过滤掉集合长度为0 或者 字符串trim()后length等于0的情形【^2】 ```java import com.fasterxml.jackson.annotation.JsonInclude; import java.util.List; // 示例:仅当列表中有元素时将其省略 @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Example { private List<String> items; // getter and setter... } ``` #### 三、具体应用场景 假设有一个用户模型User,希望在转换成json的时候如果某些字段在最终的结果集中显示出来,则可以在对应的bean上面加上相应的配置即可实现这样的需求【^2】: ```java package cn.example.model; import com.fasterxml.jackson.annotation.JsonInclude; // 当 user.name == null || "".equals(user.getName().trim()) 将会出现在 json 中 @JsonInclude(JsonInclude.Include.NON_EMPTY) public class User { private String name; // other fields... // getters & setters ... } ``` 以上就是关于 `@JsonInclude` 注解较为全面的讲解及其简单应用案例说明了。通过合理运用这个特性可以帮助开发者更灵活地管理API返回给客户端的信息结构,从而提高系统的性能并减少必要的网络流量开销。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值