简体   繁体   中英

Deserializing json with gson and retrofit

I'm currently trying to deserialize a json object that contains hundreds of objects with identical structures, like this:

“data”: {
    “1” {
        “id” : 1
        “name” : “sample”
        },
        …
    “1000” {
        “id” : 1000
        “name” : “sample”
        }
}

How would i go about doing this with gson, retrofit and rxjava? The only way I can think of is by doing the following which seems impractical.

public class Data {

    @SerializedName(“1”)
    private Item _1;
    …
    @SerializedName(“1000”)
    private Item _1000;

    Item getItem_1() {
        return _1;
    }

    void setItem_1(Item _1) {
        this._1 = _1;
    }
    …
    Item getItem_1000() {
        return _1000;
    }

    void setItem_1000(Item _1000) {
        this._1000 = _1000;
    }
}

You should change structure of your json format. Use array(square brackets) instead of 1000 objects(curly brackets).

{
“items”: [
    {
    “id” : 1
    “name” : “sample”
    },
    …
    {
    “id” : 1000
    “name” : “sample”
    }
]
}

Then your classes would be as below:

class Data{
    Item[] items;

    Item getItem(int position){
        return items[position];
    }

}

class Item{
    int id;
    String name;
}

Rather than creating a class for "data" , use Map<String, Item> . All the "1" ... "1000" will be the map keys, and you can use them or just ignore them and use Map.values() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM