Java Jackson ObjectMapper

How to work with Java and JSON? Sometimes in Java we need to work with different type data formats. One very common is JSON. In this tutorial we will see how to use popular Java library Jackson to read and write from JSON format.

To work with external libraries like jackson-databind we can download the jar and manually added to the project or we can use Maven to do this for us. In this tutorial we are using Maven.

The structure of the project look like this:

Java Maven project structure. Inside we have two classes Main and Person and pom.xml file

Let’s see our pom.xml:

XML

We use two libraries jackson-databind which is standard library if we want to work with JSON and jackson-datatype-jsr310 if we want to work with the new JAVA 8 Date/Time API (classes like LocalDate, LocalTime and LocalDateTime)

Then we have our POJO class Person:

Java

Inside we use two annotation JsonProperty (to set the output JSON property) and JsonFormat (to add specific format for LocalDate birthDate)

Then in our Main class we have methods:

  • writeSingleObjectToJSON -> for writing one java object from class Person to file target/one-person.json and also as String
  • readNodesOfJson -> reading JSON and get the nodes with JsonNode. In this case we don´t need Person class to work with the JSON
  • readObjectOfPersonFromJson -> creating Person object from JSON
  • readMapOfPersonDataFromJson -> create Map with JSON keys and JSON values. Here we also do not need Person class
  • readListOfPeopleFromJson -> create List with people from JSON
Java

Output:

Output from write Single object to JSON
{"name":"Raegan Olson","age":45,"birthDate":"1983-08-12"}
 Age of Axel Doyle is: 29 date is: 1993-08-12

Output from read Object of Person from JSON
Person from String: Person{name='Charles Beasley', age=22, birthDate=1983-08-12}

Output from read Map from JSON
Key: name has value: Tianna Fernandez
Key: age has value: 43
Key: birthDate has value: 1976-09-10

Output from read List of people
Person{name='Emma Perez', age=10, birthDate=2010-01-01}
Person{name='Alexander Joseph', age=11, birthDate=2009-01-01}

You can find GitHub repository with the example code here

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.