gpt4 book ai didi

json - 使用 Dropwizard 时配置 Jackson 映射器

转载 作者:行者123 更新时间:2023-12-03 14:37:29 26 4
gpt4 key购买 nike

我想使用 Java 8 java.timeDropwizard 的上下文中使用 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
}
}

最佳答案

JavaTimeModuleregistered 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/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com