Categories
Java Java-Json binding by Jackson Uncategorized

JSON Streaming

Jackson Streaming provides set of Streaming APIs to read from or Write to JSON as string. It is streaming oriented hence takes less memory footprint, it is analogous to Stax Streaming API for XML operations.

We will see simple example to write JSON string into .json file. Then read .json for input JSON string to be converted to Java Map object.

App.java

package custom.jackson.learning;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws IOException {
		
		//Write to JSON string to .json file
		 JsonFactory jsonFactory = new JsonFactory();
		 JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File("Employee.json"), JsonEncoding.UTF8);

		 //start writing the JSON object
		 jsonGenerator.writeStartObject();
		 
		 //"firstName":"Suresh"
		 jsonGenerator.writeStringField("firstName", "Suresh");
		 
		 //"lastName":"Rana"
		 jsonGenerator.writeStringField("lastName", "Rana");
		 
		 //"skills":["Java","PHP","SQL"]
		 jsonGenerator.writeFieldName("skills");
		 jsonGenerator.writeStartArray();
		 jsonGenerator.writeString("Java");
		 jsonGenerator.writeString("PHP");
		 jsonGenerator.writeString("SQL");
		 jsonGenerator.writeEndArray();
		 
		 //"certified":true
		 jsonGenerator.writeBooleanField("certified", true);
		 
		 //"age":21
		 jsonGenerator.writeNumberField("age", 21);
		 
		//end writing the JSON object
		 jsonGenerator.writeEndObject();
		 jsonGenerator.close();
		
		 System.out.println("JSON Writing to Employee.json completed.");
		 
		 //read the JSON file as input and convert to Map object
		 System.out.println("Reading data from Employee.json file");
		 ObjectMapper mapper = new ObjectMapper();
         Map employeeMap = mapper.readValue(new File("Employee.json"), Map.class);
         
         System.out.println("Map created from Employee.json file ::"+employeeMap);
         
	}

}


output ::

Generated Employee.json

Categories
Java Java-Json binding by Jackson

JSON parse by Tree

JSON String can also be parsed by Tree, analgous to DOM tree for XML parsing. Jackson provides the set of APIs that will take JSON string as input and it will parse it to form in-memory JSON tree. It provides set of APIs to navigate the tree.

We will see simple example to do so

Here App.java that takes input JSON string and prepares JSON tree for navigation.

package custom.jackson.learning;

import java.util.Iterator;

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

public class App {

	public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
		// TODO Auto-generated method stub

		  ObjectMapper mapper = new ObjectMapper();
	     // input JSON string
		  String jsonString = "{\"firstName\":\"Suresh\", \"lastName\":\"Rana\", "
	    		    + "	\"skill\":[\"Java\",\"PHP\",\"SQL\"] , "
	      			+ "	\"certified\":\"true\", \"age\":21}";
	      
	      //Prepare in-Memory JSON Tree
	      JsonNode rootNode = mapper.readTree(jsonString);
	      
	      
	      //Navigate the JSON Tree through Nodes and elements structure to read data.
	      JsonNode firstNameNode = rootNode.path("firstName");
	      System.out.println("First Name ::"+firstNameNode.textValue());
	      
	      JsonNode lastNameNode = rootNode.path("lastName");
	      System.out.println("First Name ::"+lastNameNode.textValue());
	      
	      JsonNode skillNode = rootNode.path("skill");
	      Iterator skillItr = skillNode.elements();
	      System.out.println("Skills are ::");
	      while(skillItr.hasNext()){
	    	  JsonNode skillName = skillItr.next();
	    	  System.out.print(skillName.textValue()+" ");
	      }
	      System.out.println();
	      JsonNode certifiedNode = rootNode.path("certified");
	      System.out.println("Certified ::"+certifiedNode.booleanValue());
	      
	      JsonNode ageNode = rootNode.path("age");
	      System.out.println("age ::"+ageNode.intValue());
	}

}


Output ::

Categories
Java Java-Json binding by Jackson

Java List to JSON

Jackson provides capability to transform primitive as well as complex data types to JSON string. Here we will see List containing Map objects transformed to JSON and vice-versa.

We use Maven, hence here is POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>custom.jackson</groupId>
  <artifactId>learning</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>learning</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
	      <groupId>junit</groupId>
	      <artifactId>junit</artifactId>
	      <version>3.8.1</version>
	      <scope>test</scope>
    </dependency>
    <dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-core</artifactId>
	    <version>2.12.3</version>
   </dependency>
   <dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-databind</artifactId>
	    <version>2.12.3</version>
	</dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-annotations</artifactId>
	    <version>2.12.3</version>
	</dependency>
  </dependencies>
</project>





Here is Project Structure

We have simple App.java file, that contains Main method to demonstrate the capability. It has List containing Maps. Each Map holds country information.

package custom.jackson.learning;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws Exception{
		
				//List of country with Capital city
				Map map1 = new HashMap();
				map1.put("Name", "India");
				map1.put("Capital", "Delhi");
				map1.put("Weather", "Hot");
				Map map2 = new HashMap();
				map2.put("Name", "Russia");
				map2.put("Capital", "Moscow");
				map2.put("Weather", "Cold");

				List<Map> countryList = new ArrayList<Map>();
				countryList.add(map1);
				countryList.add(map2);
				
				//Convert Map to JSON
				ObjectMapper mapper = new ObjectMapper();
				String jsonResult = mapper.writerWithDefaultPrettyPrinter()
				  .writeValueAsString(countryList);
				System.out.println("Convert List to JSON ::"+jsonResult);
				
				 
				List countryList2 = mapper.readValue(jsonResult, List.class);
				System.out.println("Convert JSON to List ::"+countryList2); 
				

	}

}


Output ::

As Seen in output, in first step we transform Java List to JSON. So it converts Java List into an Array of JSON Objects. In Second steps we take JSON Array as input and convert it back to Java List containing Map objects.

Categories
Java Java-Json binding by Jackson

Java Map to JSON

In this example we will see transformation of Java Map to JSON and vice-versa. JSON provides capability to map the primitive data types as well as standard collection objects. Jackson provides easy APIs to achieve it.

We use maven, so here is POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>custom.jackson</groupId>
  <artifactId>learning</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>learning</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
	      <groupId>junit</groupId>
	      <artifactId>junit</artifactId>
	      <version>3.8.1</version>
	      <scope>test</scope>
    </dependency>
    <dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-core</artifactId>
	    <version>2.12.3</version>
   </dependency>
   <dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-databind</artifactId>
	    <version>2.12.3</version>
	</dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-annotations</artifactId>
	    <version>2.12.3</version>
	</dependency>
  </dependencies>
</project>


We have simple class with Main method to demonstrate, App2.java. It contains map of country as key, capital city as value.

package custom.jackson.learning;

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class App2 {

	public static void main(String[] args) throws Exception{
		
		//Map of country with Capital city
		Map map = new HashMap();
		map.put("India", "Delhi");
		map.put("Japan", "Tokyo");
		map.put("China", "Beijing");
		map.put("USA", "New York");
		map.put("Russia", "Moscow");

		//Convert Map to JSON
		ObjectMapper mapper = new ObjectMapper();
		String jsonResult = mapper.writerWithDefaultPrettyPrinter()
		  .writeValueAsString(map);
		System.out.println("Convert Map to JSON ::"+jsonResult);
		
		 
		Map map2 = mapper.readValue(jsonResult, Map.class);
		System.out.println("Convert JSON to Map ::"+map2); 
		
		

	}

}

Output :

As seen above, in first step Map is converted to JSON string. In second step we are converting JSON String into Java.util.Map object.

Categories
Java Java-Json binding by Jackson

Binding JSON to POJO

We will see simple Java class Employee being transformed to and from JSON String.

Following is project structure generated by Maven

Following is POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>custom.jackson</groupId>
  <artifactId>learning</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>learning</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
	      <groupId>junit</groupId>
	      <artifactId>junit</artifactId>
	      <version>3.8.1</version>
	      <scope>test</scope>
    </dependency>
    <dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-core</artifactId>
	    <version>2.12.3</version>
   </dependency>
   <dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-databind</artifactId>
	    <version>2.12.3</version>
	</dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-annotations</artifactId>
	    <version>2.12.3</version>
	</dependency>
  </dependencies>
</project>


Bean class Employee.java

package custom.jackson.learning;

public class Employee {

	private String firstName;
	private String lastName;
	private boolean isCertified;
	private int age;
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public boolean isCertified() {
		return isCertified;
	}
	public void setCertified(boolean isCertified) {
		this.isCertified = isCertified;
	}
	@Override
	public String toString() {
		return "Employee [firstName=" + firstName + ", lastName=" + lastName + ", isCertified=" + isCertified + ", age="
				+ age + "]";
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	
}


package custom.jackson.learning;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
    		      ObjectMapper mapper = new ObjectMapper();
    		      String jsonString = "{\"firstName\":\"Suresh\", \"lastName\":\"Rana\", \"certified\":\"true\", \"age\":21}";
    		      
    		      try{
    		    	  
    		    	 //Transform JSON to Employee Object
    		         Employee employee_Suresh = mapper.readValue(jsonString, Employee.class);
    		         
    		         System.out.println("print Java object");
    		         System.out.println(employee_Suresh);
    		         
    		         //Transform Employee object to JSON
    		         jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee_Suresh);
    		         
    		         System.out.println("print json converted string");
    		         System.out.println(jsonString);
    		      }
    		      catch (JsonParseException e) { e.printStackTrace();}
    		      catch (JsonMappingException e) { e.printStackTrace(); }
    		      catch (IOException e) { e.printStackTrace(); }
    }
}

Output

Categories
Java Java-Json binding by Jackson Uncategorized

Jackson dependencies

Jackson libraries are distributed under Apache License as open source. We will stick to Maven as build tool. These libraries are available on Maven repositories

Following dependencies, we will add into maven project POM.xml

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

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

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.12.3</version>
</dependency>

Categories
Java Java-Json binding by Jackson

why Jackson

JSON has been way of communication since long, between systems, modules or programs, especially in times of web services. JSON format has its own advantages such as ease of use, well supported by javascript and frameworks.

Hence it leads to have a framework in place that will ease out task of JSON to Java reading, writing , transformation of JSON data to Plain java objects etc. It can reduce lot of boilterplate code while dealing with JSON formatted data.

Jackson is an open source framework distributed under Apache license to address these problems. Principally, jackson has 3 approaches to address JSON to JAVA binding

  1. Data binding APIs – It can map JSON formatted objects to Java Plain Objects(POJO). It also provides certain level of configurability to tailor the data binding.
  2. JSON Tree – Set of APIs that would read JSON formatted input document and convert the in memory tree representation of JSON, analogous to DOM tree. Then provides APIs to deal with JSON tree.
  3. Streaming API – Set of APIs to read input JSON streams, it is analogous to Stax API for XML parsing.
Categories
Java JAVA-XML BINDING

Binding Approaches

XML has been way of communication between systems, modules or programs etc. If it is the case, there is need to have framework that eases out reading from and writing to XML format and Java plain objects. It is addressed by JAXB specification.

There are multiple ways by which to and fro transformation between XML and Plain Java objects can achieved.

  1. Using DOM Parser : This approch will read input XML stream and convert the in-memory tree representation of XML. XML DOM tree can be navigated through set of APIs
  2. Using SAX Parser : This is event based framework to navigate through XML stream. We need to provider listener implmentation for SAX events in order to read/write XML data.
  3. XML JAXB Annotations : Annotations can help to transform XML stream into Plain Java objects and vice-versa. Annotations are placed on properties or accessor getter methods of Plain Java classes to achieve the mapping.
Categories
Java Java Bean Validation

Dependencies

We are going to use Maven as build tool, we will discuss this in its context.

  1. As per JSR380 specification of set of APIs provided by following
<dependency>

    <groupId>javax.validation</groupId>

    <artifactId>validation-api</artifactId>

    <version>2.0.1.Final</version>

</dependency>

2. Hibernate validator is reference implementation for above specification.

<dependency>
	    <groupId>org.hibernate.validator</groupId>
	    <artifactId>hibernate-validator</artifactId>
	    <version>6.0.13.Final</version>
</dependency>

3. Expression language dependencies to be able to write expressions in validation messages.

<dependency>
	    <groupId>org.glassfish</groupId>
	    <artifactId>javax.el</artifactId>
	    <version>3.0.0</version>
</dependency

Categories
Java Java Bean Validation

Why java bean validation

Validation is often a basic requirement for any kind of application, be it user input over web page, desktop application, mobile application or be it schematic constraints at database level or compliance of XML with respect to XSD.

Validations are implemented in several ways, at various levels in technology stack from User interface to database schema. We may restrict that “User Name” field must not be empty on login form, we may restrict that “userName” column not be empty in database table, we may restrict that in XSD that input xml tag “UserName” shouldnt be empty. Apart from this several frameworks provide their own ready to use configurable mechanisms, struts provides Validator interceptors, Hibernate provide its own annnoation over bean properties corresponding to reflect database schema.

Java bean validation can be just another approach, for several reasons. Because It is easy, because POJO java beans are used in almost all frameworks so portability ensured, or because it reduces boilerplate codes which need not be written, or because it can be looked upon as alternative to avoid to database schema, XSD xml schema or User Interface, to give performance improvement choice.

Java bean validation needs Java8 or higher version. This specification is defined by JSR380. There can be several implementations for this specification.

Design a site like this with WordPress.com
Get started