簡體   English   中英

Java - 如何遍歷 hashmap 的列表?

[英]Java - How to iterate over a list of hashmap?

我收到來自 HTTP 調用的以下響應,看起來像這樣......

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

我需要遍歷此列表並查找是否有一個名為 kids 的密鑰,如果有密鑰 kids,我需要存儲該值。 我如何在 java 中做到這一點?

首先,您需要解析 json 字符串 - 它是一個對象列表。 如果您沒有匹配這些對象的類,默認情況下它們可以表示為Map<String, Object> 然后你需要迭代列表,對於其中的每個 object,你必須迭代 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());
                }
            }
        }
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());
                }
            }
        }
    }
 

您可以使用 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM