开发者

GSON doesn't fill the list of object

I have tried several solutions and the result of parsing JSON with GSON always gets wrong.

I have the following JSON:

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

In my Java projec开发者_JS百科t I have the following structures:

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

and

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

And what I do to deserialize is:

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

At the end I'm getting List with only one element and with wrong values. Can you indicate me plase what I'm doing wrong?

Thanks.


Your javabean structure doesn't match the JSON structure (or the other way round). The account_list property in JSON basically contains an array with a single object which in turn contains different Account properties, seemingly using an index as property key. But Gson is expecting an array with multiple Account objects.

To match your javabean structure, the JSON should look like this:

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

If you can't change the JSON structure, then you have to change the Javabean structure. But since the JSON structure at its own makes little sense, it's hard to give an appropriate suggestion. A List<Map<Integer, Account>> instead of List<Account> in AccountList class will work for this. But if you'd like to keep it a List<Account>, then you need to create a custom Gson deserializer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜