我尝试了几种解决方案,使用GSON解析JSON的结果总是出错.
我有以下JSON:
{
"account_list": [
{
"1": {
"id": 1,
"name": "test1",
"expiry_date": ""
},
"2": {
"id": 2,
"name": "test2",
"expiry_date": ""
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
在我的Java项目中,我有以下结构:
public class Account{
private int id;
private String name;
private String expiry_date;
public Account()
{
// Empty constructor
}
public Account(int id, String name, String expiry_date)
{
this.id = id;
this.name = name;
this.expiry_date = expiry_date;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getExpiryDate() {
return expiry_date;
}
}
Run Code Online (Sandbox Code Playgroud)
和
public class AccountList{
private List <Account> account_list;
public void setAccountList(List <Account> account_list) {
this.account_list = account_list;
}
public List <Account> getAccountList() {
return account_list;
}
}
Run Code Online (Sandbox Code Playgroud)
而我要反序列化的是:
Data.account_list = new Gson().fromJson(content, AccountList.class);
Run Code Online (Sandbox Code Playgroud)
最后我得到List只有一个元素和错误的值.你能告诉我一下我做错了什么吗?
谢谢.
您的javabean结构与JSON结构不匹配(或反之亦然).account_listJSON中的属性基本上包含一个带有单个对象的数组,而该对象又包含不同的Account属性,似乎使用索引作为属性键.但Gson期待一个包含多个Account对象的数组.
为了匹配您的javabean结构,JSON应如下所示:
{
"account_list": [
{"id": 1, "name": "test1", "expiry_date": ""},
{"id": 2, "name": "test2", "expiry_date": ""}
]
}
Run Code Online (Sandbox Code Playgroud)
如果您无法更改JSON结构,则必须更改Javabean结构.但由于JSON结构本身没什么意义,因此很难给出适当的建议.一List<Map<Integer, Account>>,而不是List<Account>在AccountList类将进行这方面的工作.但是如果你想保留它List<Account>,那么你需要创建一个自定义的Gson反序列化器.
| 归档时间: |
|
| 查看次数: |
3854 次 |
| 最近记录: |