24

I have got GSON as a JSON parser in Java, but the keys aren't always the same.
For example. I have the following JSON:

{ "The Object I already know": {
"key1":"value1",
"key2":"value2",
"AnotherObject": { "anotherKey1":"anotherValue1", "anotherKey2":"anotherValue2" }
}

I have already got the JSONObject "The Object I already know". Now I need to get all of the JSONElements for this Object, this would be "Key1", "Key2" and "AnotherObject".
Thanks in advance.
EDIT: The Output should be a String Array with all the keys for the JSONObject

  • possible duplicate of [How to decode JSON with unknown field using Gson?](http://stackoverflow.com/questions/20442265/how-to-decode-json-with-unknown-field-using-gson) – pkubik Jun 27 '15 at 22:53
  • this could be helpful http://stackoverflow.com/questions/14619811/retrieving-all-the-keys-in-a-nested-json-in-java – Sudhansu Choudhary Jun 27 '15 at 23:01
  • what should be your final output? should it be, `"key1", "key2", "AnotherObject"` OR `"The Object I already know", "key1", "key2", "AnotherObject"` ?? – Sudhansu Choudhary Jun 27 '15 at 23:04
  • By the way I've submitted an issue and pull request to GSON to make this an inherit method. Any support may expedite it. https://github.com/google/gson/issues/941 – MarkII Oct 10 '16 at 19:53

4 Answers4

71

You can use JsonParser to convert your Json into an intermediate structure which allow you to examine the json content.

String yourJson = "{your json here}";
JsonElement element = JsonParser.parseString(yourJson);
JsonObject obj = element.getAsJsonObject(); //since you know it's a JsonObject
Set<Map.Entry<String, JsonElement>> entries = obj.entrySet();//will return members of your object
for (Map.Entry<String, JsonElement> entry: entries) {
    System.out.println(entry.getKey());
}
Michał Zalewski
  • 3,123
  • 2
  • 24
  • 37
habsq
  • 1,827
  • 16
  • 17
16

Since Java 8 you can use Streams as better looking alternative:

String str = "{\"key1\":\"val1\", \"key2\":\"val2\"}";

JsonParser parser = new JsonParser();
JsonObject jObj = (JsonObject) parser.parse(str);

List<String> keys = jObj.entrySet()
    .stream()
    .map(i -> i.getKey())
    .collect(Collectors.toCollection(ArrayList::new));

keys.forEach(System.out::println);
JaXt0r
  • 781
  • 9
  • 13
9

As of Gson 2.8.1 you can use keySet():

String json = "{\"key1\":\"val\", \"key2\":\"val\"}";

JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(json).getAsJsonObject();

Set<String> keys = jsonObject.keySet();
Michal Tenenberg
  • 518
  • 7
  • 14
4
String str = "{\"key1\":\"val1\", \"key2\":\"val2\"}";

        JsonParser parser = new JsonParser();
        JsonObject jObj = (JsonObject)parser.parse(str);

        List<String> keys = new ArrayList<String>();
        for (Entry<String, JsonElement> e : jObj.entrySet()) {
            keys.add(e.getKey());
        }

        // keys contains jsonObject's keys
Raman Shrivastava
  • 2,923
  • 15
  • 26