Java GSON: Getting the list of all keys under a JSONObject

前端 未结 4 833
孤独总比滥情好
孤独总比滥情好 2020-12-05 05:21

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

相关标签:
4条回答
  • 2020-12-05 05:35
    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
    
    0 讨论(0)
  • 2020-12-05 05:40

    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);
    
    0 讨论(0)
  • 2020-12-05 05:47

    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();
    
    0 讨论(0)
  • 2020-12-05 05:49

    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());
    }
    
    0 讨论(0)
提交回复
热议问题