How to retrieve key Information from JSON Data?


Jackson provide API’s to parse information based on Key  name.  It’s work like DOM parser and make tree of properties in JSON. Based on Path,Jackson retrieve this information for keys.

Pre-Requisite 

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  <dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.8.5</version>
  </dependency>
 

Example

In below example we have some sample JSON Data for Student and by Jackson API will try to retrieve keys information like rollNumber and phoneNumbers.

Sample DATA

{
"rollNumber" : 11,
"firstName" : "Saurabh",
"lastName" : "Gupta",
"permanent" : false,
"address" : {
"addressLine" : "Lake Union Hill Way",
"city" : "Atlanta",
"zipCode" : 50005
},
"phoneNumbers" : [ 2233445566, 3344556677 ],
"cities" : [ "Dallas", "San Antonio", "Irving" ],
"properties" : {
"play" : "Badminton",
"interst" : "Math",
"age" : "34 years"
}
}

Sample Code

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ReadJsonByKeyName {

	public static void main(String[] args) {
		try
		{
		byte[] jsonData = Files.readAllBytes(Paths.get("student_data2.txt"));

		ObjectMapper objectMapper = new ObjectMapper();

		//Jacson read JSON like DOM Parser and create tree of properties
		JsonNode rootNode = objectMapper.readTree(jsonData);

		JsonNode idNode = rootNode.path("rollNumber");
		System.out.println("rollNumber = "+idNode.asInt());

		JsonNode phoneNosNode = rootNode.path("phoneNumbers");
		Iterator<JsonNode> elements = phoneNosNode.elements();
		while(elements.hasNext()){
			JsonNode phone = elements.next();
			System.out.println("Phone No = "+phone.asLong());
		}
		}
		catch(JsonProcessingException ex)
		{
			ex.printStackTrace();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
	}
}

Output

rollNumber = 11
Phone No = 2233445566
Phone No = 3344556677

More Sample Code

For more java and JDBC codes follow below links

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Java, JSON and tagged , . Bookmark the permalink.