Jackson - Java Object Serialization / Deserialization

Basic Java Object Serialization / Deserialization

Jackson - Java Object Serialization / Deserialization

Java Objects contains the information which represents the real-world entities. These objects can be represented in other formats like JSON, XML etc. In Java, serialization is the process of converting the Java Objects to JSON, XML, or any other format. Deserialization is the opposing process that takes data from a file, stream, or network and rebuilds it into a java object.

In this article, we will explore how we can work with Java Objects and JSON format using Jackson Java Library. Jackson provides us utility functions to read and write Java Objects in JSON format. Let's start exploring this library.

Prerequisite

  • Make sure JDK is installed on your computer.
  • You can choose Maven or Gradle as your build tool. ( I am using a Maven for this article)

Step 1: Adding Jackson Dependency in pom.xml

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <jackson.version>2.12.3</jackson.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>

In your maven project add the above dependencies in the pom.xml file, you will be ready to get started.

Step 2: Preparing our Java POJO Class

Let us now create a Java POJO Class ( POJO stands for Plain Old Java Object). I have created a class representing Concert data. You can create your own POJO class.

public class Concert {
    private String concertNm;
    private String artistNm;
    private LocalDate concertDate;
    private String venueNm;

    public Concert() {
    }

    public Concert(String concertNm, String artistNm, LocalDate concertDate, String venueNm) {
        this.concertNm = concertNm;
        this.artistNm = artistNm;
        this.concertDate = concertDate;
        this.venueNm = venueNm;
    }

    public String getConcertNm() {
        return concertNm;
    }

    public String getArtistNm() {
        return artistNm;
    }

    public LocalDate getConcertDate() {
        return concertDate;
    }

    public String getVenueNm() {
        return venueNm;
    }

}

Step 3: Configuring Object Mapper Class

final ObjectMapper mapper = new ObjectMapper(); // 1
mapper.registerModule(new JavaTimeModule()); // 2
  • In Line 1 we are creating an instance of ObjectMapper, this object will provide us methods for serializing / de-serializing Java objects.
  • In Line 2 we are registering JavaTimeModule for providing support for parsing date and time-related fields.

Step 4:Convert Java Object to JSON Format (Serialization)

final Concert jacksonConcert = new Concert("Dangerous tour", 
                                           "Michael Jackson",
                                           LocalDate.of(1992, 6, 27), 
                                           "Multiple Cities");

Above we create a new instance of the Concert class.

final String JSONString =  mapper
                           .writerWithDefaultPrettyPrinter()
                           .writeValueAsString(jacksonConcert);

System.out.println(JSONString); // 3

The ObjectMapper object provides us a method writeValueAsString for writing the Java Object to JSON String. Here, the output form is in a form on String but ObjectMapper provides other methods as well to have different forms of output eg. we can directly write the JSON value to the File, etc. The method writerWithDefaultPrettyPrinter is a utility method to pretty-print the JSON value.

The output of Line 3:

{
  "concertNm" : "Dangerous tour",
  "artistNm" : "Michael Jackson",
  "concertDate" : [ 1992, 6, 27],
  "venueNm" : "Multiple Cities"
}

Step 5: Convert JSON String to Java Object (Deserialization)

final Concert concert = mapper.readValue(JSONString, Concert.class);    // 4
System.out.println(jacksonConcert.equals(concert)); // prints 'true'

Let's perform the conversion of JSON string back to Java Object. In Line 4 we are using the method readValue of the ObjectMapper class. Here the source of the value to be deserialized is of String datatype, we can also have different input sources eg. we can read JSON object directly from JSON File., etc.

In few simple steps, we got to know how to serialize and deserialize a Java Object using the Jackson library. That's it for this Dev ビット.

Bonus

Observe the output Step 4 the concertDate field of type LocalDate was represented as [ 2021, 6, 22 ] which is a little different form of representation than we usually see. To get the value in the desired format we can use the annotation @ JsonFormat in the following way:

Changes in the Concert class:

@JsonFormat(pattern = "dd-MM-yyyy")
private LocalDate concertDate;

Perform Step 4 again, the output will be following:

{
  "concertNm" : "Dangerous tour",
  "artistNm" : "Michael Jackson",
  "concertDate" : "27-06-1992",
  "venueNm" : "Multiple Cities"
}

Previous Articles

Feel free to reach out on my Twitter. Check out my other projects on my Github.

Blog_Footer_small_badge_2.png