David Fritsch
David Fritsch

Reputation: 3741

Mapping JSON to arrays/objects in Java - Android

I have a web system that returns a json string with the data that I need in an Android App. The string is below:

[
    {"id":1,
    "title":"Remove ViRuSeS",
    "tagline":"Remove ViRuSeS",
    "body":"Body",
    "image":"index.jpg",
    "steps":[
            {"id":2,
            "title":"Step 1",
            "body":"Download Things!",
            "position":1}
            ]
    }
]

It should return an array of objects, with one of the object's items also being an array of items.

I am familiar with gson and have gotten this working in the past, but I always had to simplify my data down to just an object, which makes me end up have to make multiple calls to get the data.

Is there a good way to do this without having to map all of the possible values back into classes?

My last attempt was to just try to get something simple out of this and am getting a NullPointerException on the second of these lines:

userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("Steps");

Upvotes: 3

Views: 2227

Answers (2)

Emil Adz
Emil Adz

Reputation: 41119

change it to "steps" and not "Steps" , It will fix it:

userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("steps");

The full parsing method:

JSONArray mainArray = new JSONArray(json);
for (int i = 0 ; i < mainArray.length() ; i ++)
{
    JSONObject currentItem = array.getJSONObject(i);
    String title = currentItem.getString("title");
    String body = currentItem.getString("body ");
    ....
    JSONArray currentItemStepsArray = currentItem.getJSONArray("steps"); 
    for (int j = 0 ; j < currentItemStepsArray.length() ; j ++)
    {
        ....
    }
}

Upvotes: 6

Perception
Perception

Reputation: 80623

Here, try this:

JSONArray topLevelArr = new JSONArray(json);
JSONArray stepArr = topLevelArr.getJSONObject(0).getJSONArray("steps");

Upvotes: 2

Related Questions