3

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");
1
  • 1
    Try parameter "steps" instead of "Steps" Commented Mar 16, 2013 at 19:43

2 Answers 2

6

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 ++)
    {
        ....
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the full parsing method. I think that this finally makes sense to me now!
2

Here, try this:

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

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.