0

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?

3
  • You're basically not doing anything, so you can't be wrong. Please post your entire code. Commented Mar 31, 2014 at 19:24
  • 1
    Inside the root class I think that you don't need create a new class, you need to create just public vars of type ArrayList Commented Mar 31, 2014 at 19:28
  • Go to json.org and learn the JSON syntax. Then understand that a JSON "array" is a Java List, and a JSON "object" is a Java Map. A standard JSON parser should be able to produce the Map of Lists of Maps of ... that the above represents, without any direction whatsoever. You can then pick it apart to your heart's content. Defining your own objects, for the above structure, is just extra overhead, since the objects would just contain Maps and Lists. Commented Mar 31, 2014 at 19:39

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.