3

我尝试了几种解决方案,使用 GSON 解析 JSON 的结果总是出错。

我有以下 JSON:

{
    "account_list": [
        {
            "1": {
                "id": 1,
                "name": "test1",
                "expiry_date": ""
            },
            "2": {
                "id": 2,
                "name": "test2",
                "expiry_date": ""
            }
        }
    ]
}

在我的 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;
    } 
}

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;
    }
}

我要做的反序列化是:

Data.account_list = new Gson().fromJson(content, AccountList.class);

最后我得到的 List 只有一个元素和错误的值。你能指出我做错了什么吗?

谢谢。

4

1 回答 1

9

您的 javabean 结构与 JSON 结构不匹配(或相反)。JSON 中的account_list属性基本上包含一个带有单个对象的数组,该对象又包含不同Account的属性,似乎使用索引作为属性键。Account但 Gson 期待一个包含多个对象的数组。

为了匹配您的 javabean 结构,JSON 应如下所示:

{
    "account_list": [
        {"id": 1, "name": "test1", "expiry_date": ""},
        {"id": 2, "name": "test2", "expiry_date": ""}
    ]
}

如果无法更改 JSON 结构,则必须更改 Javabean 结构。但由于 JSON 结构本身没有什么意义,因此很难给出适当的建议。AList<Map<Integer, Account>>而不是List<Account>AccountList课堂上将为此工作。但是如果你想保留它List<Account>,那么你需要创建一个自定义的 Gson 反序列化器。

于 2010-10-01T14:03:41.273 回答