Mustii1989
Mustii1989

Reputation: 29

Reading from JSON on Android

I have created an string in JSON format. It looks like:

private String jString = "{\"CategoryId\":1},{\"CategoryId\":2}";

and this is then initialized as an JSON object like this:

JSONObject jObject = new JSONObject(jString);

when reading I'm using:

j = jObject.getString("CategoryId");

I can read the first value but I can't read the second one. Any ideas on how to solve?

Upvotes: 0

Views: 625

Answers (1)

MByD
MByD

Reputation: 137282

This is not a valid JSON format. Look here to see the format of a JSON object / array.

If you want to be able to read both values, create an array:

String jString = "[{\"CategoryId\":1},{\"CategoryId\":2}]";
JSONArray jArr = new JSONArray(jString);
for (int i = 0; i < jArr.length(); ++i) {
    int i = jArr.getJsonObject(i).getInt("CategoryId");
    // do something with i which is an int, not a String
}

Upvotes: 1

Related Questions