Before going into the details of the Jackson library, let us see an application in action.
Create a Java class file named JacksonTester in C:\>Jackson_WORKSPACE.
Jackson Example
In the following example, we will create a Student class. Thereafter, we will create a JSON string with Student details and deserialize it to Student object and then serialize it back to a JSON string.Create a Java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.IOException; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; 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); mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT); jsonString = mapper.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+ " ]"; } }
Verifythe Result
Compile the classes using javac compiler as follows −C:\Jackson_WORKSPACE>javac JacksonTester.javaExecute the jacksonTester to see the result.
C:\Jackson_WORKSPACE>java JacksonTesterVerify 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 the JSON string or the source of the JSON string and the object type as parameters.//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.writeValueAsString(student);
No comments:
Post a Comment