0

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

1

Looking at the api for JsonObject, there is a method to get the keys that returns an iterator. You should be able to use this and iterate over the keys.

Sign up to request clarification or add additional context in comments.

2 Comments

What does this exactly mean? Returns an iterator of the String names in this object.
When are some other good use cases for the HashMap or Iterator classes in Android/Java? Anyone know?
0

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

0

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());
                }
            }

2 Comments

Iterator<?> keys = json.keys() will work better, json.keys() is not returning a parameterized/generic Iterator.
Just saw something very similar to this, thank you! Seems promising.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.