Friday, 15 April 2016

JSON parsing with Java

JavaScript Object Notation is a syntax for storing and exchanging of data. JSON is very lightweight hence it has become an alternative to XML.

But to use in a Java program we have to parse a JSON file and convert it into an object form. This blog demonstrate couple of ways how we can convert a JSON file to a java object.

Let us assume the below JSON file.


{
    "id" : 1,
    "name" : "Manas",
    "address" : {
      "city" : "Pune",
      "state" : "Maharastra",
      "country" : "India"
    
    }
  }




Corresponding are the Java Entity


1. Student
public class Student {
Long id;
String name;
Address address;

    Getter/Setter methods
}
 
2. Address

public class Address {
private String city;
private String state;
private String country;

Getter/setter methods 
}




Below outlined two ways of parsing JSON document to Java object.


1. Using Apache commons


This is more of a traditional way of converting JSON to JAVA object. We have to manually map each attribute of the JSON to the java instance variable.


Characteristic of this approach are 

 

1. If we add or delete or modify any attribute from JSON document we have to make corresponding  modification to the JSON parsing method to reflect the changes.
2. It is not necessary to have the JSON attribute and instance variable of Java entity to have the same name as mapping is done explicitly.
3. It is not necessary for the JSON document to be well formed.

Steps


1. Add below dependency to the pom.xml 
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>


2. Parsing method will look as shown below




2. Using fasterXML Jackson


This has become more of a standard way of parsing JSON file. 

Characteristic of this approach

 

1. We do not have to worry if any field is added or removed from JSON document . API will take care of mapping. Hence this is maintainable and scalable
2. The name of attribute in JSON document and instance variable of the java entity should be same.
3. JSON should be well formed.

Steps

 

1. Add below dependency to pom.xml
<!-- Dependency for jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.3</version>
</dependency>


2. The parsing method will look as shown below




We can configure ObjectMapper to have more control over deserialization with on/off property from DeserializationFeature.

Complete project can be found on my github repository https://github.com/manaspratimdas/blog

Resources








Saturday, 9 April 2016

Project Lombok - @Data annotation


Project Lombok is used to reduce the boilerplate code in a java class.

A normal POJO class has instance variable, setter and getter method, toString method, equals and hashCode method.

Below is a simple POJO called Student. A developer only has to type in the instance variable and rest of the code (in red box) can be generated with the help of IDE.

Taking a step further is Project Lombok. We do not even need this code(in red box). We can replace entire boilerplate code with some simple annotation.


 



Integrating Lombok in Project and Eclipse IDE

1. Add maven dependency to the pom.


<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.6</version>
            <scope>provided</scope>
        </dependency>

 
2. Download lombok.jar file from below path https://projectlombok.org/download.html. Copy to eclipse home directory and run the java -jar Lombok.jar from eclipse home directory. This will install lombok in the IDE.

Once Lombok is added to project and IDE , our previous POJO class will look like 

With single annotation @Data, Lombok add getter and setter method, equals and hashCode method and toString Method to the POJO class.

Few important point 


1. If any of the method (marked in green in above diagram) is already present in the class that will NOT be overwritten.

2. Although methods added by Lombok are not visible in the in source code they are added into the .class file. So they are present in the class file after compilation.

3. @Data annotation is combination of multiple functionality. To have more granular control we has some more annotation.

3.1 @Setter and @Getter:
     Generate setter and getter method respectively. This has an optional parameter AccessLevel that specify the access level of the method generated.
  @Getter @Setter private boolean studentId= true;
  @Setter(AccessLevel.PROTECTED) private String studentName;
  
3.2 @EqualsAndHashCode
  With this annotation we can have control over following
   A. Equals and hashcode from the superclass can be invoked
   B. Which field in the POJO class we want for equality and hashcode. We can exclude which field we do not want for equality and hashcode comparison.
  @EqualsAndHashCode(callSuper=true,exclude={"studentName")       => Here studentName will be excluded from equals and hashcode comparison

3.3 @ToString
  Similar to @EqualsAndHashCode annotation we can have more control on the fields that we want to include or exclude from toString method with @ToString annotation.
  @ToString(exclude="studentId") => This will exclude studentId from toString() methods  
  
  Lombok has few more annotation like @NonNull, @Cleanup, @Synchronized and @SneakyThrows. Those are not covered in this blog.
  
  More information on Project Lombok can be found here
  
 1.  http://jnb.ociweb.com/jnb/jnbJan2010.html
 2.  https://projectlombok.org/
 3.  https://projectlombok.org/features/

 



Streaming with Kafka API

The Kafka Streams API is a Java library for building real-time applications and microservices that efficiently process and analyze large-sca...