Search code examples
foreachmapsnested-loopsobjectmapperjsonparser

guidance with iterating over nested json and extract values


new to coding and java so trying to figure out how I can iterate over this JSON and extract the nested values

{
    "prop1": {
      "description": "",
      "type": "string"
    },
    "prop2": {
      "description": "",
      "type": "string"
    },
    "prop3": {
      "description": "",
      "type": "string"
    },
    "prop4": {
      "description": "",
      "type": "string"
    }
}

So far I have this :

public class JSONReadExample
{
  public static void main(String[] args) throws Exception {

      Object procedure = new JSONParser().parse(new FileReader("myFile.json"));
      ObjectMapper objectMapper = new ObjectMapper();

      String procedureString = objectMapper.writeValueAsString(procedure);

      Map<String, Object> map
              = objectMapper.readValue(procedureString, new TypeReference<Map<String,Object>>(){});

      map.forEach((key, value) -> System.out.println(key + ":" + value));

How can I retrieve the "type" such as "string" or "number" nested value for each key?


Solution

  • Try to specific type of Map like this:

    Map<String, LinkedHashMap<String, String>> map = objectMapper.readValue(procedureString, new TypeReference<>() {});
    

    And then you can retrieve "type" by using:

    map.forEach((key, value) -> System.out.println(key + ":" + value.get("type")));