0

I have a JSON Object which I created from a .json file which looks like the follownig:
{
  "key1": {
    "key2": "value2",
    "key3": "value3",
  }
}

To generate the JSON-Object I use:

JSONObject newJSON = new JSONObject(content);

What I want to do, is to generate a String array, which contains all keys of the existing JSONObject, to easily access them.

2

3 Answers 3

3

JSONObject implements the Map interface, so you can use the same way you'd use for Map to generate the list of keys. In particular, you can use the .keySet() or .entrySet() method.

For example (adapted from here):

JSONObject jsonObj = ...;
List<String> l = new ArrayList<String>(jsonObj.keySet());
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is incorrect. jsonObj.keySet() gives me an error "Cannot resolve method 'keySet' in 'JSONObject'".
1
         You could iterate through the keys.
          JSONObject newUserJSON = new JSONObject(content);
          ArrayList<String> keys = new ArrayList<>();
          String key;

          for (Iterator<String> it = newUserJSON.keys(); it.hasNext(); ) {
             key = it.next();
             keys.add(key);
           }
      And also you need to take care of nested json Object for each key.

Comments

1

Answer to this question is already available in another SO thread: Convert string to JSON array

Here's the equivalent for your use case:

JSONObject jsnobject = new JSONObject(content);

JSONArray jsonArray = jsnobject.getJSONArray("key1");
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject explrObject = jsonArray.getJSONObject(i);
}

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.