Home  >  Article  >  Java  >  How to solve the problem of renaming and ordering @JSONField object fields in Java

How to solve the problem of renaming and ordering @JSONField object fields in Java

王林
王林forward
2023-04-18 15:28:031720browse

Convert Java object to Json, @JSONField object field renaming and order

1. Introduce maven dependency

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.66</version>
        </dependency>

2. Field renaming

1. Create a test Entity

import lombok.Data; 
import java.io.Serializable;
 
/**
 * @类名 WeChatBusinessLicenseInfo
 * @描述 营业执照/登记证书信息(测试用)
 * @版本 1.0
 * @创建人 XuKang
 * @创建时间 2021/12/24 10:43
 **/
@Data
public class LkWeChatBusinessLicenseInfo implements Serializable {
    private static final long serialVersionUID = 1582941630439552458L;
    private String businessLicenseCopy;
    private String businessLicenseNumber;
    private String merchantName;
    private String legalPerson;
    private String companyAddress;
    private String businessTime;
    public LkWeChatBusinessLicenseInfo(){
        this.businessLicenseCopy = "1";
        this.businessLicenseNumber = "2";
        this.merchantName = "3";
        this.legalPerson = "4";
        this.companyAddress = "5";
        this.businessTime = "6";
    }
}

2. Convert the entity to a json string and see the effect before conversion

System.out.println(JSONObject.toJSONString(new LkWeChatBusinessLicenseInfo()));

{
"businessLicenseCopy":"1",
"businessLicenseNumber":"2",
"businessTime":"6",
"companyAddress":"5",
"legalPerson":"4",
"merchantName":"3 "
}

3. We need to convert to an underlined key, for example, convert businessLicenseCopy to business_license_copy

We need to modify the entity and add the annotation @JSONField

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.io.Serializable;
 
/**
 * @类名 WeChatBusinessLicenseInfo
 * @描述 营业执照/登记证书信息(测试用)
 * @版本 1.0
 * @创建人 XuKang
 * @创建时间 2021/12/24 10:43
 **/
@Data
public class LkWeChatBusinessLicenseInfo implements Serializable {
    private static final long serialVersionUID = 1582941630439552458L;
    @JSONField(name = "business_license_copy")
    private String businessLicenseCopy;
 
    @JSONField(name = "business_license_number")
    private String businessLicenseNumber;
 
    @JSONField(name = "merchant_name")
    private String merchantName;
 
    @JSONField(name = "legal_person")
    private String legalPerson;
 
    @JSONField(name = "company_address")
    private String companyAddress;
 
    @JSONField(name = "business_time")
    private String businessTime;
 
    public LkWeChatBusinessLicenseInfo(){
        this.businessLicenseCopy = "1";
        this.businessLicenseNumber = "2";
        this.merchantName = "3";
        this.legalPerson = "4";
        this.companyAddress = "5";
        this.businessTime = "6";
    }
}

4. Add annotations and print the converted json

System.out.println(JSONObject.toJSONString(new LkWeChatBusinessLicenseInfo()));

{
"business_license_copy":"1",
"business_license_number":"2",
"business_time":"6",
"company_address":"5",
"legal_person":"4",
"merchant_name":"3"
}

3. Field sorting

1. The json we output and print is like this

{
"business_license_copy":"1",
"business_license_number ":"2",
"business_time":"6",
"company_address":"5",
"legal_person":"4",
"merchant_name":"3"
}

We want to reorder the keys in a certain order

2. Add the sorting ordinal to the @JSONField annotation

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.io.Serializable;
 
/**
 * @类名 WeChatBusinessLicenseInfo
 * @描述 营业执照/登记证书信息(测试用)
 * @版本 1.0
 * @创建人 XuKang
 * @创建时间 2021/12/24 10:43
 **/
@Data
public class LkWeChatBusinessLicenseInfo implements Serializable {
 
    private static final long serialVersionUID = 1582941630439552458L;
 
    @JSONField(name = "business_license_copy",ordinal = 1)
    private String businessLicenseCopy;
 
    @JSONField(name = "business_license_number",ordinal = 2)
    private String businessLicenseNumber;
 
    @JSONField(name = "merchant_name",ordinal = 3)
    private String merchantName;
 
    @JSONField(name = "legal_person",ordinal = 4)
    private String legalPerson;
 
    @JSONField(name = "company_address",ordinal = 5)
    private String companyAddress;
 
    @JSONField(name = "business_time",ordinal = 6)
    private String businessTime;
 
    public LkWeChatBusinessLicenseInfo(){
        this.businessLicenseCopy = "1";
        this.businessLicenseNumber = "2";
        this.merchantName = "3";
        this.legalPerson = "4";
        this.companyAddress = "5";
        this.businessTime = "6";
    }
}

3. Output and print the conversion Entity:

System.out.println(JSONObject.toJSONString(new LkWeChatBusinessLicenseInfo()));
{
"business_license_copy":"1",
"business_license_number" :"2",
"merchant_name":"3",
"legal_person":"4",
"company_address":"5",
"business_time":"6"
}

##Summary: In addition to @JSONField, rename also includes @JsonProperty and @SerializedName; @JsonProperty is mainly used for input parameter conversion and Json string serialization into Java Object; @SerializedName changes the field values ​​of default serialization and default deserialization;

Common usage scenarios of @JSONField annotation

Application scenarios:

When we interact with the front end, the fields that the front end wants are different from the field names we provide. At this time, one solution is to modify the entity class, but if the entity class is used more, then change it The cost is too high, so you can use the annotation @JSONField to achieve the replacement effect. The usage is as follows:

@JSONField(name = "size_new")
private int size;

1. JSON content and entity class, @JSONField conventional writing method

JSON (with the following JSON String contents are consistent)

{
    size: 5,
    weight: 10,
    colour: "red"
}

Entity class (AppleDO.java)

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
public class AppleDO {
    @JSONField(name = "size_new")
    private int size;
    @JSONField(name = "weight_new")
    private int weight;
    @JSONField(name = "colour_new")
    private String colour;
    public int getSize() {
        return size;
    }
    public void setSize(int size) {
        this.size = size;
    }
    public int getWeight() {
        return weight;
    }
    public void setWeight(int weight) {
        this.weight = weight;
    }
    public String getColour() {
        return colour;
    }
    public void setColour(String colour) {
        this.colour = colour;
    }
}

2. Convert JSON string to corresponding Java object

Execution code

public static void main(String[] args) {
    String json = "{\n" +
        "    size_new: 5,\n" +
        "    weight_new: 10,\n" +
        "    colour_new: \"red\",\n" +
        "}";
    AppleDO appleDO = JSON.parseObject(json, AppleDO.class);
    System.out.println(appleDO.getSize());
    System.out.println(appleDO.getWeight());
    System.out.println(appleDO.getColour());
}

Running results

How to solve the problem of renaming and ordering @JSONField object fields in Java

3. Support serialization and deserialization

The default values ​​of serialization and deserialization in the source code are both true, then the default The following allows serialization and deserialization of this field, as follows:

boolean serialize() default true;
boolean deserialize() default true;

Usage method (the following does not support serialization, but supports deserialization)

@JSONField(name = "size_new", serialize = false, deserialize = true)
private int size;

When some of our fields are When the value is empty, we still want to return this field to the front end (this configuration can return a string with an empty field, but it is invalid when the field is a basic data type and must be converted to a wrapper class)

@JSONField(serialzeFeatures= SerializerFeature.WriteMapNullValue)

4. Specify the field order

Convert the Java object to JSON format. The converted field order will be sorted according to the first letter. You can also specify the field order in the following way:

@JSONField(name = "size_new", ordinal = 3)
private int size;
@JSONField(name = "weight_new", ordinal = 1)
private int weight;
@JSONField(name = "colour_new", ordinal = 2)
private String colour;

Execute Code

AppleDO apple = new AppleDO();
apple.setSize(6);
apple.setWeight(12);
apple.setColour("green");
String appleStr = JSON.toJSONString(apple);
System.out.println(appleStr);

The running result before adding the ordinal parameter


How to solve the problem of renaming and ordering @JSONField object fields in Java

The running result after adding the ordinal parameter

How to solve the problem of renaming and ordering @JSONField object fields in Java

The above is the detailed content of How to solve the problem of renaming and ordering @JSONField object fields in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete