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

前端 未结 4 844
孤独总比滥情好
孤独总比滥情好 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: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 keys = jObj.entrySet()
        .stream()
        .map(i -> i.getKey())
        .collect(Collectors.toCollection(ArrayList::new));
    
    keys.forEach(System.out::println);
    

提交回复
热议问题