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.

schande
  • 576
  • 12
  • 27
  • Please also provide information on what you have tried so far and what did not work about this, please see: https://stackoverflow.com/help/how-to-ask – Sven Hakvoort Oct 15 '18 at 10:44
  • Possible duplicate of [Json String to map convertor,](https://stackoverflow.com/questions/52799454/json-string-to-map-convertor) – Oleg Cherednik Oct 15 '18 at 10:51

3 Answers3

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());
Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
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.
Ramesh Yankati
  • 1,197
  • 9
  • 13
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);
}
Piotr Wittchen
  • 3,853
  • 4
  • 26
  • 39