Reputation: 3927
I'm receiving an JSON String in my Server which has only two parameters: name and number. Find example below:
{"name":"outlet.jpg","numbar":"2"},{"name":"image.jpg","number":"3"}, {"name":"testing.jpg","number":"1"}
I'm trying to unpack this values in a String Array. How can I do it?
This is what I have so far:
JSONObject jsonObject;
try {
jsonObject = new JSONObject(jsonString.substring(1, jsonString.length()-1));
String name = jsonObject.getString("name");
String number = jsonObject.getString("number");
System.out.println("nome: " + name + " number: " + number);
} catch (JSONException e) {
e.printStackTrace();
}
There's no getString() in jsonObject which returns an Array. This example is only getting the first element of the JSON String.. How can I receive an String Array for each key of JSON String?
Upvotes: 0
Views: 4476
Reputation: 30446
You are using the wrong type. What you want is a JSONArray.
This JSON:
[{"name":"outlet.jpg","number":"2"},{"name":"image.jpg","number":"3"}, {"name":"testing.jpg","number":"1"}]
And this code:
JSONArray json = new JSONArray(jsonString);
for(int index = 0; index < json.length(); index++) {
JSONObject jsonObject = json.getJSONObject(index);
String name = jsonObject.getString("name");
String number = jsonObject.getString("number");
System.out.println("name: " + name + " number: " + number);
}
Should produce this output:
name: outlet.jpg number: 2
name: image.jpg number: 3
name: testing.jpg number: 1
Upvotes: 5