6

I would like to use the Java 8 java.time with Jersey/Jackson in the context of a Dropwizard app. I understand I need to use jackson-modules-java8 and configure the mapper object.

But how do I configure Jersey's automagic mapper that deserialises the incoming JSON for me? I.e. where would I do mapper.registerModule(new JavaTimeModule());?

To illustrate the current situation here is an example class that represents the incoming JSON:

public class Example {
  // Want to use java.time instead
  private Date date;
  private final String ISO_OFFSET_DATE_TIME = "YYYY-MM-DD'T'HH:mm:ssZ";

  @JsonCreator
  public Example(@JsonProperty("date") 
                 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = ISO_OFFSET_DATE_TIME) 
                 Date date) {
    this.date = date;
  }

  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = ISO_OFFSET_DATE_TIME)
  public Date getDate() {
    return date;
  }
}

As you can see that uses the older Date API. The Jersey resources looks like the following:

@Path("/example")
@Consumes(MediaType.APPLICATION_JSON)
public class ExampleResource {
  @POST
  public void consume(Example example) {
    // Do stuff with example.date
  }
}
Friedrich 'Fred' Clausen
  • 3,321
  • 8
  • 39
  • 70

1 Answers1

7

JavaTimeModule is registered by default in Dropwizard 1.0.0 and above. For previous versions, the dropwizard-java8 bundle provided support for Java 8 features. Java 8 is the baseline for Dropwizard 1.0.0, and the bundle was merged into baseline.

Assuming you use Dropwizard 1.0.0 or above, if you still need to access the ObjectMapper, you can do it in your Application<T>:

  • in method void initialize(Bootstrap<T> bootstrap), via bootstrap.getObjectMapper()
  • in method abstract void run(T configuration, Environment environment), via environment.getObjectMapper()

That way, you can register other modules, or enable or disable Jackson features. Some of them impact how Java 8 types are serialized and deserialized.

vin59
  • 148
  • 7