I have a json file
{"apple" : [
{
"first" : 3,
"second" : 5,
}
],
"orange" : [
{
"fst" : 7,
"snd" : 8,
}
],
}
a helper class for deserialization
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.
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:
/* .... */
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
? Currently, I get SerializedName is not a repeatable annotation type
error.
You need to use @SerializedName
in Helper class (and update MyDesClass
if needed):
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
:
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;
}
// ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.