1

I have this json structure in a JSONObject:

{
 "images":
 {
 "-KEHe39xfHoRmK9gPxpv": 
  {
  "image": "",
  "imei": "000000000000000",
  "latitude": "",
  "longitude": ""
  }, 
 "-KEHe5BOpHz6WlKF_F5B": 
   {
   "image": "",
   "imei": "000000000000000",
   "latitude": "",
   "longitude": ""
  },
 "-KEHe73aFp59v5Y_mX0Z": 
  {
  "image": "",
  "imei": "000000000000000",
  "latitude": "",
  "longitude": ""
  }
 }
}

As you can see, the keys are unique. I know that when I do

jsonArray = jsonObject.getJSONArray("images");

... I can get the values of the corresponding key.

My problem is that I don't know the keys. So I can't put them into .getJSONArray() in order to get my values back.

I tried to get the arrays of the arrays

jsonArray = jsonObject.getJSONArray("images").getJSONArray(x); // x == 0 , 1 , 2 , 3
String test = jsonArray.toString();
textView.setText(test);

Gives me this output

04-03 20:41:16.073 9080-9080/com.example.app W/System.err: org.json.JSONException: Value {"-KEHe8nN5iFyGCIXiuv-":{"image":"DATA","longitude":"DATA","latitude":"DATA","imei":"000000000000000"},"-KEHe5BOpHz6WlKF_F5B":{"image":"DATA","longitude":"DATA","latitude":"DATA","imei":"000000000000000"},"-KEHe39xfHoRmK9gPxpv":{"image":"DATA"
04-03 20:41:16.073 9080-9080/com.example.app W/System.err:     at org.json.JSON.typeMismatch(JSON.java:100)
04-03 20:41:16.077 9080-9080/com.example.app W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:548)

*I replaced the actual data in the output...

TSchieck
  • 49
  • 1
  • 4

2 Answers2

0

The images element is not an array. It's an object. You can get it like this:

JSONObject images = jsonObject.getJSONObject("images");

Then you can iterate its unique keys like this to get a hold of the objects associated with each key:

for (String key : images.keys()) {
    JSONObject image : images.getJSONObject(key);
}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • This answer together with that one https://stackoverflow.com/questions/9151619/java-iterate-over-jsonobject solved my problem. Thanks – TSchieck Apr 03 '16 at 23:36
0

Yes, if it was a JSONArray it would have square brackets. The example you gave is a tree of JSONObject.

Veener
  • 4,771
  • 2
  • 29
  • 37