Use @ JSONField annotation in fastjason

Posted by gtomescu on Mon, 01 Nov 2021 05:55:11 +0100

In a recent project, the json format was used to transfer data between servers. However, it is found that json format data does not comply with the variable definition rules in JAVA and is difficult to understand. Therefore, secondary processing needs to be done in the background to process the data into the format defined in our system.

Idea:

    1. Define the bean to be returned, and define the data to be returned in the bean

    2. Get the JSON string to be processed

    3. Convert JSON string into bean, and then return the converted bean to the client.

Because the key in json cannot match the attribute in bean, some attributes are null during conversion. After checking the official documents, it is found that @ JSONField can be used for explanation, but there is no detailed instructions.

@Action object of JSONField:

1. Field
2. Setter and Getter methods

Note: fastjason operates according to getter and setter methods, not according to Field.

Show me the code:

1, Action Field

@When JSONField acts on a Field, its name defines not only the name of the input key, but also the name of the output.
The code is as follows:

import com.alibaba.fastjson.JSONObject;  
import com.alibaba.fastjson.annotation.JSONField;  
  
public class Person {  
    @JSONField(name="name")  
    private String name;  
      
    @JSONField(name="age")  
    private String age;  
      
    @JSONField(name="desc")  
    private String desc;  
      
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public String getAge() {  
        return age;  
    }  
    public void setAge(String age) {  
        this.age = age;  
    }  
    public String getDesc() {  
        return desc;  
    }  
    public void setDesc(String desc) {  
        this.desc = desc;  
    }  
      
    public void setNAME(String NAME) {  //If it does not take effect, the value of name in the annotation on the field is "name", then the setter is setName
        this.name = NAME;  
    }  
      
    public void setAGE(String AGE) {  //If it does not take effect, the value of name in the annotation on the field is "name", then the setter is setAge
        this.age = AGE;  
    }  
      
    public void setDESC(String DESC) {  //If it does not take effect, the value of name in the annotation on the field is "name", then the setter is setDesc
        this.desc = DESC;  
    }  
      
    public String toString() {  
        return JSONObject.toJSONString(this);  
    }  
}  

 

 

 

The output is as follows:

 
bean to json:{"age":"20","desc":"Just a test","name":"xianglj"}  
To be converted json:{"AGE":"20","DESC":"Just a test","NAME":"XIANGLJ"}  
json to bean:null  

From the above, we can see that @ JSONField defines input and output when it acts on a file. If the json format we transmit does not conform to this format, it cannot be converted correctly.

2, Acts on setter and getter methods

As the name suggests, when acting on a setter method, it is equivalent to looking for the corresponding value in json according to the name and calling the setter object for assignment.

When acting on a getter, when the bean is converted to json, its key value is the value defined by name. Examples are as follows:

import com.alibaba.fastjson.JSONObject;  
import com.alibaba.fastjson.annotation.JSONField;  
  
public class Product {  
  
    private String productName;  
    private String desc;  
    private String price;  
      
    @JSONField(name="name")  
    public String getProductName() {  
        return productName;  
    }  
      
    @JSONField(name="NAME")  
    public void setProductName(String productName) {  
        this.productName = productName;  
    }  
      
    @JSONField(name="desc")  
    public String getDesc() {  
        return desc;  
    }  
      
    @JSONField(name="DESC")  //There is a toUpperCase operation on jsonStr in the test code. This will match "DESC"
    public void setDesc(String desc) {  
        this.desc = desc;  
    }  
      
    @JSONField(name="price")  
    public String getPrice() {  
        return price;  
    }  
      
    @JSONField(name="PRICE")  
    public void setPrice(String price) {  
        this.price = price;  
    }  
      
    public String toString() {  
        return JSONObject.toJSONString(this);  
    }  
      
}  

 

import org.java.json.fastjson.bean.Product;  
import org.junit.Test;  
  
import com.alibaba.fastjson.JSONObject;  
  
/** 
 * Test the JSON transformation in fastjson 
*/  
public class JsonObjectTest {  
  
    public static void main(String[] args) {  
        Product product = new Product();  
        product.setProductName("product");  
        product.setDesc("This is a product");  
        product.setPrice("22.3");  
          
        String jsonStr = JSONObject.toJSONString(product);  
        System.out.println("Convert to json:" + JSONObject.toJSONString(product));  
          
        //jsonStr = jsonStr.toUpperCase();  
        System.out.println(jsonStr);  
          
        product = JSONObject.toJavaObject(JSONObject.parseObject(jsonStr), Product.class);  
        System.out.println(product.toString());  
    }  
      
    @Test  
    public void test() {  
        Product product = new Product();  
        product.setProductName("product");  
        product.setDesc("This is a product");  
        product.setPrice("22.3");  
          
        String jsonStr = JSONObject.toJSONString(product);  
        System.out.println("Convert to json:" + JSONObject.toJSONString(product));  
          
        jsonStr = jsonStr.toUpperCase();  
        System.out.println(jsonStr);  
          
        product = JSONObject.toJavaObject(JSONObject.parseObject(jsonStr), Product.class);  
        System.out.println(product.toString());  
    }  
} 

The output is as follows:

Convert to json:{"desc":"This is a product","name":"product","price":"22.3"}  
{"DESC":"This is a product","NAME":"product","PRICE":"22.3"}  
{"desc":"This is a product","name":"product","price":"22.3"}  

With this annotation, we do not need to manually assign values to properties that cannot be converted when converting bean s. Even if the returned data is changed in the future, it can be modified quickly. You don't have to change the code. Just modify the annotation name value.

That's all for this annotation. I hope you like it and support it

http://blog.csdn.net/u011425751/article/details/51219242

 

 

fastjson is a JSON serialization and deserialization library with excellent performance provided by Alibaba, and it is easy to use. We can use JSON.toJSONString(object) to serialize an object into JSON format, but what if we don't want to serialize all members of a class.

There are two ways to solve this problem:

1. Add the transient attribute -- java feature to the attribute that does not want to be serialized

2. Add or remove JSONField(serialize=false)---fastjson feature to attributes that do not want to be serialized

 

A friendly reminder:

Due to the deserialization vulnerability in the lower version of fastjson, we recommend that you use a newer version, at least above version 1.2.28
---------------------
By John Huster
Source: CSDN
Original text: https://blog.csdn.net/john1337/article/details/76276073
Copyright notice: This article is the original article of the blogger. Please attach the blog link for reprint!

 

Function: ignore some attributes in Java beans during json serialization, and serialization and deserialization will be affected.

Usage method: it is generally marked on an attribute or method, and the returned json data does not contain the attribute.

Scene simulation:

You need to convert a list < historyorderbean > into json format and pass it to the foreground. However, the values of the basic attribute fields in the entity class are stored in the snapshot attribute field. At this time, I can handle it in the business layer and assign the value of the snapshot attribute field to the corresponding basic attribute field in the entity class. Finally, I hope the returned json data does not contain these two snapshot fields, so annotate @ JsonIgnore on the snapshot attribute in the entity class, and the last returned json data will not contain the two attribute values of goodsInfo and extendsInfo.

public class HistoryOrderBean {

//Basic attribute fields
private String insurantName;
private String insuranceName;
private String insurancePrice;
private String insurancePicture;
private String insuranceLimit;

//Snapshot attribute field
@JsonIgnore
private String goodsInfo; // Snapshot basic information
@JsonIgnore
private String extendsInfo; // Snapshot extended attribute information

}

4. Notes invalid:
If the annotation fails, it may be because you are using fastjason. Try to use the corresponding annotation to ignore the field. The annotation is @ JSONField(serialize = false). The use method is the same.
---------------------
Author: fakerswe
Source: CSDN
Original text: https://blog.csdn.net/fakerswe/article/details/78626085
Copyright notice: This article is the original article of the blogger. Please attach the blog link for reprint!

 

Topics: Spring Boot