I am facing a JSON issue and do not know to approach it. I am trying to obtain a JSONArray though the application will never know the corresponding name to this data set. For example, we have something like the following data set:
{"Kobe":[{"Location":"LA","Position":"PG"}]}
Normally to obtain the value corresponding with Kobe I would use:
contentArray = json.getJSONArray("Kobe");
By doing this I would obtain the array that has two elements, Location and Position. My question is, what happens if I do not know that the name is "Kobe". I need to somehow dynamically at run time get the appropriate name to pass into the .getJSONArray() function. The application is blind and unaware of the name value pairs until the data actually arrives from the server. Any ideas, thoughts, code snippets are welcome.
Thanks.
4 Answers 4
This should work for you:
String value = "{\"Kobe\":[{\"Location\":\"LA\",\"Position\":\"PG\"}]}\r\n";
JSONObject obj = new JSONObject(value);
JSONArray array = null;
for (Iterator<?> keys = obj.keys(); array == null && keys.hasNext();) {
array = obj.optJSONArray((String) keys.next());
}
// array will now contain null if no array was found or the first array encountered.
Comments
You could try something like
JSONObject json = new JSONObject("{\"key1\":\"String\",\"key2\":[1,2,3,4,5], \"key3\":[\"str1\", \"str2\"]}");
Iterator<String> keys = json.keys();
for(;keys.hasNext();) {
String key = keys.next();
Object obj = json.get(key);
if (obj instanceof JSONArray) {
JSONArray array = (JSONArray) obj;
Log.d("Ololo", array.toString());
}
}
I use the library google.com.gson
In that case you can just map your json object with a simple class and then passing an array of those:
...
class Coordinates {
String location;
String position;
}
...
then you can use the method fromJson like this:
Coordinates[] array = fromJson(data, Coordinates[].class);