【发布时间】:2021-06-14 21:58:19
【问题描述】:
我的 JSON 响应是这样的:
{
"General": {
"Code": "xyz",
"People": {
"0": {
"Name": "abc"
},
"1": {
"Name": "def..."
},
"AddressData": {
"Street": 123,
"ZIP": 456
}
}
}
}
对象 1 和 2 是同一个对象。它们将始终具有相同的属性。但是,取决于我何时提取 JSON,它们可能不仅仅是两个对象。我不确定如何使用 Gson 反序列化数据。
我尝试过使用:
@SerializedName("People")
@Expose
private People[] People;
人们在哪里:
private class People {
@SerializedName("Name")
@Expose
private String name;
public People(String name){
this.name = name
}
}
但是,我得到了错误
java.lang.IllegalStateException: 应为 BEGIN_ARRAY,但在第 1 行是 BEGIN_OBJECT
我的普通班是:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class General {
@SerializedName("Code")
@Expose
private String code;
@SerializedName("People")
@Expose
private People[] people;
@SerializedName("AddressData")
@Expose
private AddressData addressData;
private class People {
@SerializedName("Name")
@Expose
private String name;
public People(String name){
this.name = name;
}
}
private class AddressData {
@SerializedName("Street")
@Expose
private String street;
@SerializedName("ZIP")
@Expose
private String zip;
}
}
【问题讨论】:
-
响应中的 People 是一个地图,只需将 People[] 更改为 hashmap
就可以了。要将它们转换为数组,可以使用 People.value().toArray();
标签: java json serialization gson