Apr 28, 2018

How to convert JSON String to JSON Object and fetch Specific part of JSON : Without specifying Java Class name convert JSON string to Object

It is common use case to retrieve information from JSON without converting in into Java Object. Suppose we retrieve a JSON string as response from some service and we want to retrieve some information from it and we do not have Java  class which response can directly map to.

If we have Java class available we can directly map response with Java class using readvalue() API of Jackson as follows:
objectMapper.readValue(responseString, <RESPONSE_CLASS_NAME>.class);

Suppose we do not have RESPONSE_CLASS available or we do not want to map whole response to any Java class & retrieve information from JSON directly.

Using Jasckosn JsonNode : Convert JSON String to JsonNode and access Json as key/value from tree structure. We can reach from one node to another node and retrieve details without converting into Java class.

Consider below JSON String response and our goal is to find Blood group of all employees.
{
 "status": "SUCCESS",
 "payload": {
  "employees": [{
    "employeeId": "015823300000500788",
    "department": "1524637468898",
    "personalDetails": {
     "firstName": "Nikhil",
     "lastName": "Ranjan",
     "address": {
      "addressLineNumber1": "House# 206",
      "addressLineNumber2": "SLS APRTMENT",
      "zip": 560043,
      "state": "Karnataka",
      "country": "INDIA",
      "landmark": "HSR Layout"
     },
     "bloodGroup": "O+"
    },
    "designation": "Senior Engineer"
   },
   {
    "employeeId": "015823300000500788",
    "department": "1524637468898",
    "personalDetails": {
     "firstName": "Rahul",
     "lastName": "kant",
     "address": {
      "addressLineNumber1": "House# 96",
      "addressLineNumber2": "ARP Road",
      "zip": 560086,
      "state": "Karnataka",
      "country": "INDIA",
      "landmark": "BTM Layout"
     },
     "bloodGroup": "B+"
    },
    "designation": "Lead Engineer"
   }
  ]
 }
}

Sample program:
Here we have used Jackson cor API jar and converted JSON string to JsonNode and later retrieved list of all employees as ArrayNode. Iterate ArrayNode and retrieve relevant information forn JsonNode.

package com.devinline;

import java.io.IOException;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
/**
 * 
 * @author nikhil(www.devinline.com)
 * 
 */
public class JSONStringToObject {

 public static void main(String[] args) throws IOException {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  /*Convert JSON String to JsonNode */
  JsonNode responseJsonNode = objectMapper.readTree(response);
  /*Retrieve payload node from JsonNode */
  JsonNode payloadJsonNode = responseJsonNode.get("payload");
  /*Retrieve Employees list node from payload */
  ArrayNode employeesArray = (ArrayNode) payloadJsonNode.get("employees");
  
  /*Iterate over ArrayNode and retrieve details*/
  for (JsonNode employee : employeesArray) {
   JsonNode personalDetailsNode = employee.get("personalDetails");
   String bloodGroup = personalDetailsNode.get("bloodGroup").asText();
   String firstName = personalDetailsNode.get("firstName").asText();
   System.out.println("Blood group of " + firstName + " is : " + bloodGroup);
  }

 }

 public static final String response = "{\n" + 
   "\"status\": \"SUCCESS\",\n" + 
   "\"payload\": {\n" + 
   "    \"employees\": [\n" + 
   "        {\n" + 
   "            \"employeeId\": \"015823300000500788\",\n" + 
   "            \"department\": \"1524637468898\",\n" + 
   "            \"personalDetails\":{\n" + 
   "                \"firstName\": \"Nikhil\",\n" + 
   "                \"lastName\": \"Ranjan\",\n" + 
   "                \"address\": {\n" + 
   "                    \"addressLineNumber1\": \"House# 206\",\n" + 
   "                    \"addressLineNumber2\": \"SLS APRTMENT\",\n" + 
   "                    \"zip\": 560043,\n" + 
   "                    \"state\": \"Karnataka\",\n" + 
   "                    \"country\": \"INDIA\",\n" + 
   "                    \"landmark\": \"HSR Layout\"\n" + 
   "                },\n" + 
   "                \"bloodGroup\": \"O+\"\n" + 
   "            },\n" + 
   "            \"designation\": \"Senior Engineer\"\n" + 
   "        },\n" + 
   "        {\n" + 
   "            \"employeeId\": \"015823300000500788\",\n" + 
   "            \"department\": \"1524637468898\",\n" + 
   "            \"personalDetails\":{\n" + 
   "                \"firstName\": \"Rahul\",\n" + 
   "                \"lastName\": \"kant\",\n" + 
   "                \"address\": {\n" + 
   "                    \"addressLineNumber1\": \"House# 96\",\n" + 
   "                    \"addressLineNumber2\": \"ARP Road\",\n" + 
   "                    \"zip\": 560086,\n" + 
   "                    \"state\": \"Karnataka\",\n" + 
   "                    \"country\": \"INDIA\",\n" + 
   "                    \"landmark\": \"BTM Layout\"\n" + 
   "                },\n" + 
   "                \"bloodGroup\": \"B+\"\n" + 
   "            },\n" + 
   "            \"designation\": \"Lead Engineer\"\n" + 
   "        }\n" + 
   "    ]\n" + 
   "}\n" + 
   "}";
 }

Sample Output
:

Blood group of Nikhil is : O+
Blood group of Rahul is : B+

Pom.xml entry for jackson jar
:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.5</version>
</dependency>

Reference:
https://github.com/zytham/JSONPlayWithJackson