tags:

views:

68

answers:

1

Hello,

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 project 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.

+4  A: 

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.

BalusC
Ok, probably I will have to introduce Objects in my php file which is generating JSON, because after extracting data from db, I'm trying to put it directly to arrays and send responce. Thanks going to review php file.
Serhiy
Ah right, associative arrays in PHP indeed generate weird JSON like this. Geez, much luck with this :)
BalusC
Done, thanks for help!
Serhiy
You're welcome.
BalusC