简体   繁体   English

在 JAVA 中的 JSON 反序列化期间更改两个文件名

[英]Changing two filed names during JSON deserialization in JAVA

I have a json file我有一个 json 文件

{"apple" : [
        {
            "first"    : 3,
            "second"    : 5,

        }
      ],
"orange" : [
        {
            "fst"    : 7,
            "snd"    : 8,

        }
      ],
}

a helper class for deserialization用于反序列化的助手 class


public class Helper {

    private int num1;

    private int num2;

    public Helper(Helper other) {
        this.num1 = other.num1;
        this.num2 = other.num2;
    }

    public int getNum1() {
        return this.num1;
    }

    public int getNum2() {
        return this.num2;
    }
}

A java class for deserialization, which I need to change the JSON keys to be compatible with instance names of the Helper class. A java class 用于反序列化,我需要将 JSON 键更改为与Helper ZABC42ABBBA2F2ZED2DC94 的实例名称兼容。

public class MyDesClass {

    @SerializedName(value = "apple.first", alternate = "apple.num1")
    @SerializedName(value = "apple.seconds", alternate = "apple.num2")
    private final Helper[] apple;

    public MyDesClass(Helper[] apple) {
        this.apple = apple;
    }
    
}          

And, also inside main.java I have:而且,在 main.java 里面我有:

/* .... */
        Reader f = new FileReader( PATH_TO_THE_JSON_FILE);
        Gson gson = new Gson();
        GameBoard gameBoard = gson.fromJson(f, MyDesClass.class);
/* .... */

My question is how can I convert two values (eg first and second ) at the same time (eg to num1 and num2 here) in MyDesClass ?我的问题是如何在MyDesClass中同时转换两个值(例如firstsecond )(例如这里的num1num2 )? Currently, I get SerializedName is not a repeatable annotation type error.目前,我得到SerializedName is not a repeatable annotation type错误。

You need to use @SerializedName in Helper class (and update MyDesClass if needed):您需要在 Helper class 中使用@SerializedName (并在需要时更新MyDesClass ):

public class Helper {

    @SerializedName(value = "first" alternate={"num1","fst"})
    private int num1;

    @SerializedName(value = "second" alternate={"num2","snd"})
    private int num2;

    public Helper(Helper other) {
        this.num1 = other.num1;
        this.num2 = other.num2;
    }

    public int getNum1() {
        return this.num1;
    }

    public int getNum2() {
        return this.num2;
    }
}

To comply with the updated JSON, MyDesClass needs to have another field orange :为了符合更新后的 JSON, MyDesClass需要有另一个字段orange

public class MyDesClass {

    @SerializedName("apple")
    private final Helper[] apple;

    @SerializedName("orange")
    private final Helper[] orange;

    public MyDesClass(Helper[] apple, Helper[] orange) {
        this.apple = apple;
        this.orange = orange;
    }
// ...    
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM