首页 > 解决方案 > Java从嵌套的json中提取键值

问题描述

我确实有以下 JSON,我正在尝试在结果中提取对象

{
   "status":true,
   "results":{
      "type1":{
         "id":"type1"
      },
      "type2":{
         "id":"type2"
      }
   }
}

所需的输出是

type1,type2

我正在使用 Gson 进行序列化和反序列化。

标签: javaapigsonrest-assured

解决方案


这些是您在使用 gson 时应该执行的步骤

  1. 获取单独在“结果”中的 json 对象的键
  2. 将其作为具有键和值的 json 对象获取
  3. 收集我们的 JSON 的条目集
  4. 创建一个迭代器,以便稍后您可以提取键

这是执行相同工作的代码:

public static void main(String[] args) throws Exception {
        
        String json = "{\r\n" + 
                "   \"status\":true,\r\n" + 
                "   \"results\":{\r\n" + 
                "      \"type1\":{\r\n" + 
                "         \"id\":\"type1\"\r\n" + 
                "      },\r\n" + 
                "      \"type2\":{\r\n" + 
                "         \"id\":\"type2\"\r\n" + 
                "      }\r\n" + 
                "   }\r\n" + 
                "}";
        
        JsonParser parser = new JsonParser();
        JsonObject obj = parser.parse(json).getAsJsonObject();
        
        //get keys of the json objects which are inside "results" alone
        //get it as json object which has keys and values
        //collect the entry set our of the JSON
        //create an iterator so that later you can extract the keys
        Iterator<Entry<String, JsonElement>> iterator = obj.get("results")
                                                            .getAsJsonObject()
                                                            .entrySet()
                                                            .iterator();
        
        while(iterator.hasNext()) {
            //here you will get the keys like - type1 and type2
            System.out.println(iterator.next().getKey());
        }
    
    }

代码编辑: @fluffy 指出的内容完全有意义。做出改变


推荐阅读