JackSon的忽略注解

JackSon的忽略注解

在本教程中,我将通过一个示例向您展示如何在使用 Jackson @JsonIgnore、@JsonIgnoreProperties 和 @JsonIgnoreType注释将对象序列化为 JSON 时忽略某些字段。这些注解用于忽略 JSON 序列化和反序列化中的逻辑属性

@JsonIgnore用于忽略序列化和反序列化中使用的逻辑属性。@JsonIgnore 可用于 setter、getter 或字段。

@JsonIgnoreProperties忽略 JSON 序列化和反序列化中的指定逻辑属性。它在类级别进行了注释。

@JsonIgnoreType在类级别进行了注释,它忽略了整个类。

Maven依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

用@JsonIgnoreProperties 在类级别忽略字段
我们可以在类级别忽略特定字段,使用@JsonIgnoreProperties注释并指定字段:

package net.javaguides.jackson.ignore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(value = {
    "id",
    "firstName"
})
public class CustomerDTO {
    private final String id;
    private final String firstName;
    private final String lastName;
 
    public CustomerDTO(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
 
    public String getId() {
        return id;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
}

请注意,我们忽略了CustomerDTO的两个字段****“id”“firstName” ,只打印了“lastName”

使用@JsonIgnore 在字段级别忽略字段

package net.javaguides.jackson.ignore;
 
import com.fasterxml.jackson.annotation.JsonIgnore;
 
public class CustomerDTO {
 
    @JsonIgnore
    private final String id;
 
    @JsonIgnore
    private final String firstName;
    private final String lastName;
 
    public CustomerDTO(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
 
    public String getId() {
        return id;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
}

请注意,我们使用@JsonIgnore注释忽略了CustomerDTO的两个字段****“id”“firstName” ,并且只打印了“lastName”

使用@JsonIgnoreType 按类型忽略所有字段

package net.javaguides.jackson.ignore;
 
import com.fasterxml.jackson.annotation.JsonIgnoreType;
 
public class UserDTO {
 
    public int id;
    public Name name;
 
 
    public UserDTO(int id, Name name) {
        super();
        this.id = id;
        this.name = name;
    }
 
    @JsonIgnoreType
    public static class Name {
        public String firstName;
        public String lastName;
        public Name(String firstName, String lastName) {
            super();
            this.firstName = firstName;
            this.lastName = lastName;
        }
    }
}

请注意,使用@JsonIgnoreType注释会忽略 Name 类字段。

posted @   CH_song  阅读(112)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示