简体   繁体   中英

Parsing key - object JSON with GSON

How can I parse this JSON using GSON?

{
    "1" : [
        {
            "id" : 1,
            "images" : [
                {},
                {},
                ...
            ]
        },
        {},
        ...
    ],
    "2" : [
            {},
        {},
        ...
    ],
    ...
}

I ran out of ideas how to parse it. I was trying to use map but objects were null.

My classes:

public class Root {
    private HashMap<Integer, FirstObject> objects; 
}

public class FirstObject {
    private List<SecondObject> objects;
}

public class SecondObject {
    private int id;
    private List<Image> images;
}

public class Image {
    ...
}

What I'm doing wrong?

Use a tool to generate your Java classes from your JSON. Something like JSONSchema2Pojo

public class Root {
    @SerializedName("1")
    @Expose
    private List<Album> _1 = new ArrayList<Album>();

    @SerializedName("2")
    @Expose
    private List<Album> _2 = new ArrayList<Album>();

    ...
}

Solves my problem.

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