Mahyar Mahyar - 1 year ago 77
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

objectMapper
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:

[
{
"id":10,
"firstName":"Jack",
"primaryPhone":"9999999999",
"email":"[email protected]"
},
{
"id":4,
"firstName":"Mark",
"primaryPhone":"9999999991",
"email":"[email protected]"
},
{
"id":12,
"firstName":"Susaan",
"primaryPhone":"9999999992",
"email":"[email protected]"
}
]


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

For example if
id=4
, read the
firstName
and
email
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();
    if(id.equals("4")){
        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);
        break;
    }
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download