Testing custom JSON serialization

At the time of writing Jackson converter in version 2.4.6 doesn't support javax.time.LocalDate out of the box. Therefore you need to create your own JsonSerializer and JsonDeserializer. A pretty strait forward implementation could look like this:

public class LocalDateSerializer extends JsonSerializer<LocalDate> {
  public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    jgen.writeString(value.toString());
  }
}

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
  public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    return LocalDate.parse(jp.getText());
  }
}

The more interesting part are the Junit tests. Here I learned how to convert JSON into objects and vice versa with a few lines of code. First we need a Sample class containg a java.time.LocalDate:

private static class Sample {

  @JsonSerialize(using = LocalDateSerializer.class)
  @JsonDeserialize(using = LocalDateDeserializer.class)
  private final LocalDate orderDate = parse("2015-10-07");

  public LocalDate getOrderDate() {
    return orderDate;
  }
}

Just a plain POJO. Let's look at the deserialize test fist:

@Test
public void shoudProperlyDeserializeLocalDateIntoJson() throws IOException {
  Sample actual = new ObjectMapper().readValue("{\"orderDate\":" + "\"2015-10-07\"" + "}", Sample.class);

  assertEquals(2015, actual.getOrderDate().getYear());
  assertEquals(10, actual.getOrderDate().getMonthValue());
  assertEquals(7, actual.getOrderDate().getDayOfMonth());
}

Just one line of code to create an object from a JSON string. Nice. And the counterpart: Creating a JSON string from an object.

@Test
public void shoudProperlySerializeLocalDateToJson() throws IOException {

  String actual = new ObjectMapper().writeValueAsString(new Sample());

  assertEquals("{\"orderDate\":\"2015-10-07\"}", actual);
}

Again a single line of code...cool.

Show Comments