How can we read only specific properties from json in java - using Jackson

Maven dependency -

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
Or Download - bundle (1.3 MB) 

If you are beginner don't worry learn how to Create new Maven project - In 2 minutes

How can we read only specific properties(nodes) from json in java - using Jackson Api


import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertJsonToJavaObject {

    public static void main(String[] args) {
          try {
                 ObjectMapper objectMappernew ObjectMapper();

                 // Convert JSON string to java Object
                 String jsonInString"{\"empId\":11,\"emp_name\":\"Ankit\",\"address\":[\"Paris\",\"London\"]}";
                
                 JsonNode rootNodeobjectMapper.readTree(jsonInString);

                
                
                
                
                 //READ empId
                 System.out.println("1. empId value = "+rootNode.get("empId") + ", empId type = "+rootNode.get("empId").getNodeType());

                 //OR
                 JsonNode empIdrootNode.path("empId");
                 System.out.println("1. empId value = "+empId", empId type = "+empId.getNodeType());
        


                
                 //READ emp_name
                 System.out.println("\n2.emp_name value = "+rootNode.get("emp_name") + ", emp_name type = "+rootNode.get("emp_name").getNodeType());

                
                
                
                 //READ address
                 System.out.println("\n3.address value = "+rootNode.get("address") + ", address type = "+rootNode.get("address").getNodeType());


          catch (JsonGenerationException e) {
                 e.printStackTrace();
          catch (JsonMappingException e) {
                 e.printStackTrace();
          catch (IOException e) {
                 e.printStackTrace();
          }
    }

}

//output
/*
1. empId value = 11, empId type = NUMBER
1. empId value = 11, empId type = NUMBER

2.emp_name value = "Ankit", emp_name type = STRING

3.address value = ["Paris","London"], address type = ARRAY

*/


Related links >

1. Jackson JSON -

We can use Jackson api for for processing JSON in java.

Jackson JSON examples


2. Java provides API (JSR 353) for Processing  JSON (JSR 353).
It provides -
  • Object Model API
  • Streaming API

Java API for JSON processing examples >



3. Simple  (simple.JSONObject)



4. Google Gson - processing java json


eEdit
Must read for you :