JSON: Treat many objects as array of object

118 Views Asked by At

I have a JSON Like this

{ "video":{  
        "video_3745":{  },
        "video_3437":{  },
        "video_3471":{  },
        "video_4114":{  }
      }
}

In which every "video_xxxx" is of the SAME type. Is there a way to treat the "video" field as an array of that type? I need to iterate over all the videos, but the API is not sending them in an array, and I don't know how to model a class to receive this JSON without having to manually specify all the field names...

does GSON or LoganSquare have anything to help me out with this?

2

There are 2 best solutions below

0
On

You can't treat them as an array, but with the org.json.JSONObject class you can get the list of keys and iterate over them. I believe in GSON the JsonObject.entrySet method will allow something similar.

https://developer.android.com/reference/org/json/JSONObject.html https://google.github.io/gson/apidocs/com/google/gson/JsonObject.html

0
On

Try something like this

JSONObject video= json.getJSONObject("video"); // json is the whole response
Iterator x = video.keys();
JSONArray jsonArray = new JSONArray();

while (x.hasNext()){
    String key = (String) x.next();
    jsonArray.put(video.get(key));
}