简体   繁体   中英

How to read the root nodes when they only have a value using Jackson?

I read in a valid JSON file, which has the format shown below (I have no control in that) with only values for the root nodes, using:

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
JsonNode rootNode = jsonMapper.readTree(belowString);
  1. How do I get the root nodes names (First and second below), which I do not know?
  2. Subsequently, I also need to read the attending value
{
"First": [{

        "name": "Bill",
        "groupName": "team1",
        "groupType": "golf",
        "info": [{
            "name": "George",
            "groupName": "Caddy"
        }],
        "attending": false
    },
    {
        "name": "Fred",
        "groupName": "team2",
        "groupType": "golf",
        "info": [{
            "name": "Todd",
            "groupName": "caddy"
        }],
        "attending": false
    },
    {
        "name": "Mike",
        "groupName": "team3",
        "groupType": "golf",
        "info": [{
            "name": "Peter",
            "groupName": "caddy"
        }],
        "attending": false
    }
],
"Second": [{

    "name": "Alan",
    "groupName": "team4",
    "groupType": "golf",
    "info": [{
        "name": "Tony",
        "groupName": "caddy"
    }],
    "attending": false
}]
}

The accepted answer solved #1. This is the resolution I used for #2 to access the nested nodes:

while (iter.hasNext()) {
   Map.Entry<String, JsonNode> entry = iter.next();

   System.out.println("key: " + entry.getKey());
   System.out.println("value: " + entry.getValue());

   if (entry.getValue().isArray()) {
       JsonNode attending = entry.getValue().get(1).get("attending");
       System.out.println("attending = " + attending.toString());
   }
}

You are almost there! Find below a quick snippet. Hope this will help.

JsonNode node = mapper.readTree( "{\"First\":[{\"name\":\"Bill\",\"groupName\":\"team1\",\"groupType\":\"golf\",\"info\":[{\"name\":\"George\",\"groupName\":\"Caddy\"}],\"attending\":false},{\"name\":\"Fred\",\"groupName\":\"team2\",\"groupType\":\"golf\",\"info\":[{\"name\":\"Todd\",\"groupName\":\"caddy\"}],\"attending\":false},{\"name\":\"Mike\",\"groupName\":\"team3\",\"groupType\":\"golf\",\"info\":[{\"name\":\"Peter\",\"groupName\":\"caddy\"}],\"attending\":false}],\"Second\":[{\"name\":\"Alan\",\"groupName\":\"team4\",\"groupType\":\"golf\",\"info\":[{\"name\":\"Tony\",\"groupName\":\"caddy\"}],\"attending\":false}]}".getBytes() );
node.fields().forEachRemaining( entry -> System.out.println( "Key "+ entry.getKey() + " Value "+ entry.getValue()) );

Output:

Key First Value [{"name":"Bill","groupName":"team1","groupType":"golf","info":[{"name":"George","groupName":"Caddy"}],"attending":false},{"name":"Fred","groupName":"team2","groupType":"golf","info":[{"name":"Todd","groupName":"caddy"}],"attending":false},{"name":"Mike","groupName":"team3","groupType":"golf","info":[{"name":"Peter","groupName":"caddy"}],"attending":false}]
Key Second Value [{"name":"Alan","groupName":"team4","groupType":"golf","info":[{"name":"Tony","groupName":"caddy"}],"attending":false}]

To get the field names:

Iterator<String> iter = rootNode.fieldNames();
while (iter.hasNext()) {
    System.out.println("field: " + iter.next());
}

To get the names and the values:

Iterator<Entry<String, JsonNode>> iter = rootNode.fields();
while (iter.hasNext()) {
    Entry<String, JsonNode> entry = iter.next();
    System.out.println("key: " + entry.getKey());
    System.out.println("value: " + entry.getValue());
}

You could also deserialize this Json as a Map with readValue(..) if readTree(..) is not a requirement, like:

@Test
public void test() throws Exception {
    ObjectMapper jsonMapper = new ObjectMapper();
    // JSON contains this kind of a structure
    Map<String, List<Map<String, Object>>> map = jsonMapper
                // test.json should be in the same package as test and contain 
                // your Json
                .readValue(getClass().getResourceAsStream("test.json"), Map.class);
    // Result of this loggion below
    map.entrySet().forEach(entry -> {
        log.info("key: {}", entry.getKey());
        entry.getValue().forEach(person -> {
            log.info(" {} attending: {}", person.get("name"), person.get("attending"));
        });
    });
}

Log should be like:

key: First
Bill attending: false
Fred attending: false
Mike attending: false
key: Second
Alan attending: false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM