Technology Sharing

SpringBoot Annotation--11--@JSONField @JsonProperty

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right.


A question: The attributes starting with isXXX in the backend entity class are automatically removed after being transferred to the front end.

insert image description here

insert image description here
insert image description here
insert image description here
insert image description here

Solution:

  1. Change the name of the generated isReceipt() method to getIsReceipt()
  2. Add the @JsonProperty(value = "isXXX") annotation to the generated get method, which is isReceipt.
 @JsonProperty(value = "isReceipt")
    public boolean isReceipt() {
        return isReceipt;
    }
    @JsonProperty(value = "isExamine")
    public boolean isExamine() {
        return isExamine;
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

insert image description here

@JsonProperty and @JSONField

1 Introduction

  • @JsonProperty and @JSONField annotations are forWhen converting obj to json string, replace the java bean property name with the target property nameThis is common in scenarios where attribute names are inconsistent when calling third-party interfaces.
  • The two annotations have the same purpose, but they come from different sources and are used in different ways. The following will explain their similarities and differences in detail!

2. Differences in annotations

2.1 Different underlying frameworks

  • @JsonProperty is implemented by Jackson
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>版本号</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • @JSONField is implemented by fastjson
         <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>版本号</version>
        </dependency>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.2 Different scopes

@JSONproperty annotation is used forAttributesabove

  • For example, to serialize the trueName attribute as name, you can add @JsonProperty(value="name") above the attribute name.

The @JSONField annotation can be usedget, set, and propertiesabove

  • For example, to serialize the trueName attribute as name, you can add @JSONField(value="name") above the get/set/attribute name.

2.3 Comparison of advantages and disadvantages

  1. The @JSONField annotation is simpler to use. The default value of the annotation is the same as the attribute name, while @JsonProperty requires manual specification of the attribute name.

  2. The @JSONField annotation supports more attribute mapping options, such as date format during serialization, handling of null values, etc.

  3. @JSONField annotation has faster performance, because fastjson itself is a high-performance JSON processing library

  4. When using the Jackson framework, you can only use the @JsonProperty annotation, not the @JSONField annotation.

@JsonProperty

If you are using a newly createdspringboot project, Jackson serialization is the default, and annotations can be used directly on the attributes.

1. Dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>版本号</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • The @JsonProperty annotation comes from the jackson package and is used with the ObjectMapper().writeValueAsString(entity class) method to convert the entity class into a json string.
  • Used with ObjectMapper().readValue(string) method to convert json string into entity class.

2. Test the conversion between json string and bean object

Entity class: User.java

import com.fasterxml.jackson.annotation.JsonProperty;
 
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
	@JsonProperty("JsonPropertyName")
	private String name;
	private String sex;
	private Integer age;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Test Methods:

@Test
public void testJsonProperty() throws IOException{
    //bean ---> json
	User user=new User("zhangsan","man",22);
	
	System.out.println(new ObjectMapper().writeValueAsString(user));
	

    //json ---> bean
	String str="{"sex":"man","age":22,"JsonPropertyName":"zhangsan"}";
	
	System.out.println(new ObjectMapper().readValue(str, User.class).toString());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

Test Results:

{"sex":"man","age":22,"JsonPropertyName":"zhangsan"}
User [name=zhangsan, sex=man, age=22]
  • 1
  • 2
  • It can be seen that after the bean is converted into a json string, the bean property name annotated with @JsonProperty has been replaced with the specified property name: JsonPropertyName;

  • After the json string is converted to a bean, the property name specified by the @JsonProperty annotation has been replaced with the bean property name: name;

@JSONField

1. Dependency

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>版本号</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • @JSONField is located in the fastjson package and is used with the JSON.toJSONString(entity class) method to convert the entity class into a JSON string.
  • Used with the JSON.parseObject(string, entity class.class) method to convert the json string into an entity class.

2. Test the conversion between json string and bean object

Entity class: User.java

import com.alibaba.fastjson.annotation.JSONField;
 
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
	@JSONField(name="JSONFieldName")
	private String name;
	private String sex;
	private Integer age;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Test Methods:

@Test
public void testSONField(){
    //bean ---> json
	User user=new User("zhangsan","man",22);
	System.out.println(JSON.toJSONString(user));
	
    //json ---> bean
	String str="{"JSONFieldName":"zhangsan","age":22,"sex":"man"}";
	System.out.println(JSON.parseObject(str, User.class).toString());	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Test Results:

{"JSONFieldName":"zhangsan","age":22,"sex":"man"}
User [name=zhangsan, sex=man, age=22]
  • 1
  • 2
  1. It can be seen that after the bean is converted into a JSON string, the bean attribute name annotated with @JSONField has been replaced with the specified attribute name: JSONFieldName;
  2. After the json string is converted to a bean, the attribute name specified by the @JSONField annotation has been replaced with the bean attribute name: name;
  3. The test results are the same as @JsonProperty.

3.format attribute

The format attribute can be used to specify the format of date type attributes and the format of converting numeric types to string types.

public class User {
    private String name;
    private int age;
    @JSONField(format = "yyyy-MM-dd")
    private Date birthday;
    @JSONField(format = "#,###.00")
    private double salary;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • In the above example, the @JSONField annotation is used to specify the date format of the birthday attribute as "yyyy-MM-dd"
  • The salary attribute has a numeric format of "#,###.00"

4. serialize attribute

  • The serialize property can be used to control whether the property is serialized into the JSON object.
  • When the serialize property is false, the property will not be serialized into the JSON object. The default value is true
public class User {
    @JSONField(serialize = false)
    private int userId;
    private String name;
    private int age;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

In the above example, the userId property is excluded from serialization using the @JSONField annotation.

5.deserialize attribute

  • The deserialize property can be used to control whether the properties in the JSON object are deserialized into the Java object.
  • When the deserialize property is false, the property will not be deserialized from the JSON object to the Java object. The default value is true
public class User {
    private int userId;
    private String name;
    @JSONField(deserialize = false)
    private int age;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

In the above example, the age property is excluded from deserialization using the @JSONField annotation.

6.ordinal attribute

The ordinal attribute can be used to specify the order of attributes.

  • By default, the order of the properties is based on the order in which they appear in the Java object.
public class User {
    @JSONField(ordinal = 2)
    private String name;
    @JSONField(ordinal = 1)
    private int age;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

In the above example, the @JSONField annotation is used to specify the order of the age attribute as 1 and the order of the name attribute as 2.

7.defaultValue attribute

The defaultValue attribute can be used to specify the default value of a property in a Java object.

public class User {
    @JSONField(defaultValue = "0")
    private int userId;
    @JSONField(defaultValue = "N/A")
    private String name;
    private int age;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

In the above example, the @JSONField annotation is used to specify the default value of the userId attribute as 0 and the default value of the name attribute as "N/A"

8. type attribute

  • The type attribute can be used to specify the type of the attribute.
public class User {
    private int userId;
    @JSONField(type = FieldType.STRING)
    private int age;
}
  • 1
  • 2
  • 3
  • 4
  • 5

In the above example, the @JSONField annotation is used to specify that the type of the age attribute is a string type.