English 中文(简体)
Jackson - First Application
  • 时间:2024-12-22

Jackson - First Apppcation


Previous Page Next Page  

Before going into the details of the jackson pbrary, let s see an apppcation in action. In this example, we ve created Student class. We ll create a JSON string with student details and deseriapze it to student object and then seriapze 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;

pubpc class JacksonTester {
   pubpc 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;
   pubpc Student(){}
   pubpc String getName() {
      return name;
   }
   pubpc void setName(String name) {
      this.name = name;
   }
   pubpc int getAge() {
      return age;
   }
   pubpc void setAge(int age) {
      this.age = age;
   }
   pubpc 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: DeSeriapze 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: Seriapze Object to JSON.

Use writeValueAsString() method to get the JSON string representation of an object.

//Object to JSON Conversion		
jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
Advertisements