Close

Jackson JSON - Registering custom serializer and deserializer

[Updated: Jun 1, 2018, Created: Jun 1, 2018]

Following example shows how to write custom serializer and deserializer and how to register them with ObjectMapper.

Example

Java Object

public class CurrencyRate {
  private String pair;
  private double rate;
  private LocalDateTime lastUpdated;
    .............
}

Custom JsonSerializer

package com.logicbig.example;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.FormatStyle;

public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
  static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);

  @Override
  public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider)
          throws IOException {
      try {
          String s = value.format(DATE_FORMATTER);
          gen.writeString(s);
      } catch (DateTimeParseException e) {
          System.err.println(e);
          gen.writeString("");
      }
  }
}

Custom JsonDeserializer

package com.logicbig.example;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;

public class LocalDatetimeDeserializer extends JsonDeserializer<LocalDateTime> {

  @Override
  public LocalDateTime deserialize(JsonParser p, DeserializationContext ctx)
          throws IOException {
      String str = p.getText();
      try {
          return LocalDateTime.parse(str, LocalDateTimeSerializer.DATE_FORMATTER);
      } catch (DateTimeParseException e) {
          System.err.println(e);
          return null;
      }
  }
}

Main class

package com.logicbig.example;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.IOException;
import java.time.LocalDateTime;

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      System.out.println("-- Java object to JSON --");
      CurrencyRate cr = new CurrencyRate();
      cr.setPair("USD/JPY");
      cr.setRate(109.15);
      cr.setLastUpdated(LocalDateTime.now());
      System.out.println("Java object: " + cr);

      ObjectMapper om = new ObjectMapper();

      //creating a module
      SimpleModule module = new SimpleModule();
      //adding our custom serializer and deserializer
      module.addSerializer(LocalDateTime.class ,new LocalDateTimeSerializer());
      module.addDeserializer(LocalDateTime.class, new LocalDatetimeDeserializer());
      //registering the module with ObjectMapper
      om.registerModule(module);

      String s2 = om.writeValueAsString(cr);
      System.out.println("JSON string: " + s2);

      System.out.println("-- JSON to Java object --");
      CurrencyRate cr2 = om.readValue(s2, CurrencyRate.class);
      System.out.println("Java Object: " + cr2);
  }
}
-- Java object to JSON --
Java object: CurrencyRate{pair='USD/JPY', rate=109.15, lastUpdated=2018-06-01T20:52:47.102579200}
JSON string: {"pair":"USD/JPY","rate":109.15,"lastUpdated":"Jun 1, 2018, 8:52:47 PM"}
-- JSON to Java object --
Java Object: CurrencyRate{pair='USD/JPY', rate=109.15, lastUpdated=2018-06-01T20:52:47}

Using @JsonSerialize and @JsonDeserialize

Instead of registering our custom Serializer and Deserializer with ObjectMapper, we can use @JsonSerialize and @JsonDeserialize, check out this example.

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.5: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 10
  • Maven 3.3.9

Registering custom serializer and deserializer Select All Download
  • jackson-serialize-deserialize-module-registration
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java

    See Also