Mahyar Mahyar -3 years ago 114
JSON Question

jackson - read specific field from string list of jsons

I'm pretty new to world of jackson, and wanted to read the value of specific field from list of jsons (which is a response body of third-party api).

for a single json, using

works fine.

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(sampleString);
JsonNode idNode = rootNode.path("id");
System.out.println("id: "+ idNode.asText());

But I want to parse list of jsons (which is a string coming from a response body)
.So for example I receive this body:


I want to read the
s first, and if I find a specific id, return some other info from that block.

For example if
, read the
of that person.

But I'm not sure how to parsee list of json.

Any suggestions/comments is appreciated.

Answer Source

You can try,

JsonNode array = objectMapper.readValue(sampleString, JsonNode.class);
 for(int i=0;i<array.length;i++){
    JsonNode jsonNode = array.get(i);
    JsonNode idNode = jsonNode.get("id");
    String id = idNode.asText();
        JsonNode firstNameNode = jsonNode.get("firstName");
        String firstName = firstNameNode.asText();
        System.out.println("firstName = " + firstName);
        JsonNode emailNode = jsonNode.get("email");
        String email = emailNode.asText();
        System.out.println("email = " + email);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download