Monday, February 25, 2019

Jackson - First Application

Before going into the details of the jackson library, let's see an application in action. In this example, we've created Student class. We'll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.IOException;

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

public class JacksonTester {
   public static void main(String args[]){
   
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
      
      //map json to student
      try{
         Student student = mapper.readValue(jsonString, Student.class);
         
         System.out.println(student);
         
         jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
         
         System.out.println(jsonString);
      }
      catch (JsonParseException e) { e.printStackTrace();}
      catch (JsonMappingException e) { e.printStackTrace(); }
      catch (IOException e) { e.printStackTrace(); }
   }
}

class Student {
   private String name;
   private int age;
   public Student(){}
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Student [ name: Mahesh, age: 21 ]
{
  "name" : "Mahesh",
  "age" : 21
}

Steps to remember

Following are the important steps to be considered here.

Step 1: Create ObjectMapper object.

Create ObjectMapper object. It is a reusable object.
ObjectMapper mapper = new ObjectMapper();

Step 2: DeSerialize JSON to Object.

Use readValue() method to get the Object from the JSON. Pass json string/ source of json string and object type as parameter.
//Object to JSON Conversion
Student student = mapper.readValue(jsonString, Student.class);

Step 3: Serialize Object to JSON.

Use writeValueAsString() method to get the JSON string representation of an object.
//Object to JSON Conversion  
jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);

No comments:

Post a Comment

Popular Posts