抢号专区

JackSon的忽略注解

Less than a minute to read

JackSon的忽略注解

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

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

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

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

Maven依赖

com.fasterxml.jackson.core

jackson-databind

2.9.8

用@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 类字段。


Copyright © 2088 时效性网游活动中心 All Rights Reserved.
友情链接