Home > Enterprise >  Java - How to iterate over a list of hashmap?
Java - How to iterate over a list of hashmap?

Time:01-21

I have a following response from a HTTP call which looks like this...

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

I need to iterate through this list and find if there is a key called kids and if there is the key kids, i need to store the value . How do i do it in java?

CodePudding user response:

First you need to parse the json string - it's a list of objects. If you don't have classes to match those objects, by default they can be represented as Map<String, Object>. Then you need to iterate the list, and for every object in it, you have to iterate the entries in the object. If the key matches, store it.

        //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());
                }
            }
        }

CodePudding user response:

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());
                }
            }
        }
    }
 
  •  Tags:  
  • Related