【问题标题】:Java - How to iterate over a list of hashmap?Java - 如何遍历哈希图列表?
【发布时间】:2022-01-21 08:48:08
【问题描述】:

我有一个来自 HTTP 调用的以下响应,看起来像这样......

[{"id": 1, "name" : abc, "above50" :  true} , {"id": 2, "name" : "xyc", "above50" :  false, "kids" : "yes"} ]

我需要遍历此列表并查找是否有一个名为 kids 的密钥,如果有密钥 kids,我需要存储该值。我在java中是如何做到的?

【问题讨论】:

    标签: java json list hashmap literate-programming


    【解决方案1】:

    首先你需要解析 json 字符串——它是一个对象列表。如果您没有匹配这些对象的类,默认情况下它们可以表示为Map<String, Object>。然后你需要迭代列表,并且对于其中的每个对象,你必须迭代对象中的条目。如果密钥匹配,则存储它。

            //parse json string with whatever parser you like
            List<Map<String, Object>> list = ...;
            //iterate every object in the list
            for (Map<String, Object> map : list) {
                //iterate every entry in the object
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    if (entry.getKey().equals("kids")) {
                        //you can store the key and the value however you want/need
                        System.out.println(entry.getKey() + " -> " + entry.getValue());
                    }
                }
            }
    

    【讨论】:

      【解决方案2】:
      import com.fasterxml.jackson.databind.JsonNode;
      import com.fasterxml.jackson.databind.ObjectMapper;
      -------------------------------------------
      
          @Test
          public void test04() throws IOException {
              final String preString = "[{\"id\": 1, \"name\" : \"abc\", \"above50\" :  true} , {\"id\": 2, \"name\" : \"xyc\", \"above50\" :  false, \"kids\" : \"yes\"} ]";
              final ObjectMapper objectMapper = new ObjectMapper();
              final JsonNode arrayNode = objectMapper.readTree(preString);
              if (arrayNode.isArray()) {
                  for (JsonNode it : arrayNode) {
                      final JsonNode kids = it.get("kids");
                      if (kids != null) {
                          //TODO: Storage this value by you want
                          System.out.println(kids.asText());
                      }
                  }
              }
          }
       
      

      【讨论】:

        【解决方案3】:

        你可以使用 JSONObject 或 JSONArray

        String message = ""list" : [{"id": 1, "name" : abc, "above50" :  true} , {"id": 2, "name" : "xyc", "above50" :  false, "kids" : "yes"} ]";
        JSONObject jsonObject = new JSONObject(message);
        JSONArray array = jsonObject.getJsonArray("list");
        //so now inside the jsonArray there is 2 jsonObject
        //then you can parse the jsonArray and check if there is 
        //a jsonObject that have "kids" like jsonObject.get("kids") != null
        // or jsonObject.getString("kids") != null
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-01-21
          • 2019-03-11
          • 1970-01-01
          • 2014-06-01
          • 1970-01-01
          • 2018-07-29
          • 2013-02-25
          相关资源
          最近更新 更多