Using Jackson we can easily deserialize a JSON Object into a Java Object. The following example takes a file Person.json and creates a new Person java object using the contents.
Jackson by default will map the keys in the json file to the fields in your java object. Notice the key names in Person.json map to the fields in the java Person object.
- Line 2 in
Person.jsonmaps to line 10 inPerson.java - Line 3 in
Person.jsonmaps to line 11 inPerson.java - Line 4 in
Person.jsonmaps to line 12 inPerson.java
Person.json
1 2 3 4 5 | { "firstName": "John", "lastName": "Smith", "age": 25 } |
- Create a new
ObjectMapper
On line 69 we create ObjectMapper which is what reads the json file and produces a Java Object. - Call
mapper.readValueto deserialize
mapper.readValuetakes 2 arguments. The first argument in this example is a newFileobject using the path to thePerson.jsonobject relative to the base of our project directory. The second argument is the class that is produced, in this exmaple this is thePerson.classseen from lines 9 through 25.
JacksonJson.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | package nibs.io.json; import java.io.File; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonJson { public static class Person { private String firstName; private String lastName; private int age; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } } public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(new File("./Person.json"), Person.class); System.out.println(person.getFirstName()); System.out.println(person.getLastName()); System.out.println(person.getAge()); } } |
Console Output
John
Smith
25
Reference: http://wiki.fasterxml.com/JacksonHome