Jackson

Posted by Wh0ami-hy on January 30, 2024

1. 常用的Jackson注解

1.1. @JsonProperty

属性级别的注解,它主要有以下几个常用的属性

value

指定 JSON 中的属性名称,如果不设置则使用 Java 属性名。

public class User {
    @JsonProperty(value="FirstName")  // 在序列化和反序列化时将以 FirstName 进行
    private String firstName;
}

defaultValue

指定属性的默认值,如 @JsonProperty(defaultValue = "abcd")

required

指定属性是否是必填的,在反序列化时如果缺失该属性会抛出异常。如:@JsonProperty(required = true)

access

控制属性的读写权限,可选值有 READ_ONLYWRITE_ONLY 和 READ_WRITE。例如:@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)

1.2. @JsonIgnore

在序列化和反序列化时,忽略某个属性

public class User {
    @JsonIgnore  // 在序列化和反序列化时将忽略 firstName
    private String firstName;
}

1.3. @JsonIgnoreProperties

加在类上,用于在序列化和反序列化时,忽略类中的多个属性

@JsonIgnoreProperties({"bar", "baz"}) // 在序列化和反序列化时将忽略 bar 和 baz
public class MyClass
{
    private String foo;
    private String bar;
    private Integer baz;
    ...
}

1.4. @JsonPropertyOrder

加在类上,用于在序列化和反序列化时,更改属性的排列顺序

@JsonPropertyOrder(value = {"lastName","firstName"})
public class MyClass {
    private String firstName;
    private String lastName;
}

序列化结果

// 默认
{
  "firstName" : "Harrison",
  "lastName" : "Ford"
}

// 修改顺序后
{
  "lastName" : "Ford",
  "firstName" : "Harrison"
}

1.5. @JsonIgnoreType

加在类上,当该类作为其他类的子类时,在序列化和反序列化时,会忽略该类

@JsonIgnoreType
public class Address {
    private String address1;
    ...
}

public class MyClass {
    private Address address;
    private String firstName;
    private String lastName;
}

序列化结果

{
  "firstName" : "Harrison",
  "lastName" : "Ford"
}

1.6. @JsonFormat

在序列化某些类型(尤其是日期)时,设置序列化和反序列化的格式

public class MyClass
{
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createdDate;
}

1.7. @JsonUnwrapped

加在类上,当该类作为其他类的子类时,在序列化和反序列化时,自动按一定规则解包(prefix属性)

public class Address {
    private String address1;
    private String address2;
    private String city;
    private String state;
    private String zip;
}

public class MyClass {
    private String firstName;
    private String lastName;
    @JsonUnwrapped
    private Address address;
}

序列化结果

// 常规情况下的序列化结果
{
  "firstName" : "Harrison",
  "lastName" : "Ford",
  "address" : {
    "address1" : "123 Main Street",
    "address2" : null,
    "city" : "Hollywood",
    "state" : "CA",
    "zip" : "33023"
  }
}

// 没有添加前缀解包规则
{
  "firstName" : "Harrison",
  "lastName" : "Ford",
  "address1" : "123 Main Street",
  "address2" : null,
  "city" : "Hollywood",
  "state" : "CA",
  "zip" : "33023"
}

// 添加前缀解包规则
{
  "firstName" : "Harrison",
  "lastName" : "Ford",
  "addr.address1" : "123 Main Street",
  "addr.address2" : null,
  "addr.city" : "Hollywood",
  "addr.state" : "CA",
  "addr.zip" : "33023"
}

1.8. @JsonGetter

1.9. @JsonAnyGetter and @JsonAnySetter

1.10. @JsonValue


本站总访问量