我想使用 Java 8 java.time在 Dropwizard 的上下文中使用 Jersey/Jackson应用程序。我知道我需要使用 jackson-modules-java8并配置映射器对象。
但是如何配置 Jersey 的自动映射器来为我反序列化传入的 JSON? IE。我在哪里做mapper.registerModule(new JavaTimeModule());
?
为了说明当前情况,这里有一个表示传入 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;
}
}
如您所见,它使用较旧的 Date API。 Jersey 资源如下所示:
@Path("/example")
@Consumes(MediaType.APPLICATION_JSON)
public class ExampleResource {
@POST
public void consume(Example example) {
// Do stuff with example.date
}
}
最佳答案
JavaTimeModule
是 registered by default在 Dropwizard 1.0.0 及更高版本中。对于以前的版本,dropwizard-java8 bundle 提供了对 Java 8 功能的支持。 Java 8 是 Dropwizard 1.0.0 的基准,捆绑包是 merged into baseline .
假设您使用 Dropwizard 1.0.0 或更高版本,如果您仍然需要访问 ObjectMapper
, 你可以在你的 Application<T>
:
void initialize(Bootstrap<T> bootstrap)
, 通过 bootstrap.getObjectMapper()
abstract void run(T configuration, Environment environment)
, 通过 environment.getObjectMapper()
这样,您可以注册其他模块,或启用或禁用 Jackson 功能。其中一些影响how Java 8 types are serialized and deserialized .
关于json - 使用 Dropwizard 时配置 Jackson 映射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53440362/