fastjson simple use demo

The @JSONField annotation is on the attribute field and the set and get methods. Convert custom json string to entity class, and convert entity class to json;

The @JSONField annotation is on the attribute field and the set and get methods. Use the @Data annotation to manually override the setter/getter method for the attribute [pseudonym]

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;

@Data
public class Stu {

    private String name;
    //下划线自动转换
    private String alias_name;

    //下划线自动转换
//    @JSONField(name="pen_name")
    private String penName;

    //实体类转为json,使用注解name值
    @JSONField(name="pen_name2")
    private String penName2;


    private String pseudonym;

    //实体类转为json,使用注解name值
    @JSONField(name="pseud")
    //不使用注解为属性名{"penName":"333","name":"1111","alias_name":"222","pen_name2":"444","pseudonym":"555"}
    public String getPseudonym() {
        return pseudonym;
    }

    //json转为实体类,使用注解name值
    @JSONField(name="pseudo")
    public void setPseudonym(String pseudonym) {
        this.pseudonym = pseudonym;
    }

    public static void main(String[] args) {
        String json = "{'name':'1111','aliasName':'222','pen_name':'333','pen_name2':'444','pseudo':'555'}";
        Stu stu = JSON.parseObject(json, Stu.class);

        System.out.println(stu);
        System.out.println(JSONObject.toJSON(stu));
    }
}

operation result

Stu(name=1111, alias_name=222, penName=333, penName2=444, pseudonym=555)
{"pseud":"555","penName":"333","name":"1111","alias_name":"222","pen_name2":"444"}

Process finished with exit code 0

Note:

The @JsonProperty
annotation provides the name corresponding to the java property during serialization and deserialization.
Access.WRITE_ONLY: Use the modified field only during serialization
Access.READ_ONLY: Use it only during deserialization, similar to the @JsonAlias ​​annotation Access.READ_WRITE: Use the modified field Access.AUTO
during both serialization and deserialization
: Automatically determined

The @JsonAlias
​​annotation is only available in Jackson version 2.9.
The function is to allow the Bean's properties to receive the names of multiple json fields during deserialization. Can be added to fields or getter and setter methods

Guess you like

Origin blog.csdn.net/qq_44031685/article/details/130890878