【问题标题】:GSON doesn't fill the list of objectGSON 未填写对象列表
【发布时间】:2010-10-01 13:55:28
【问题描述】:

我尝试了几种解决方案,但使用 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);

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

谢谢。

【问题讨论】:

    标签: java json gson


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 好的,可能我必须在生成 JSON 的 php 文件中引入对象,因为从数据库中提取数据后,我试图将其直接放入数组并发送响应。感谢您查看 php 文件。
    • 啊,对了,PHP 中的关联数组确实会生成像这样奇怪的 JSON。天哪,这很幸运:)
    猜你喜欢
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多