首页 > 解决方案 > 日期序列化忽略 REST 请求中的 ContextResolver

问题描述

我有一个基于 Wildfly 15 的应用程序,它使用 Yasson 序列化 REST 请求中的实体。我使用 javaee-api 8.0.1 并创建了一个ContextResolver用于配置日期序列化格式的文件,如https://stackoverflow.com/a/56300246/584532

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JsonbDateConfig implements ContextResolver<Jsonb> {
  // ...
}

但是,当使用以下代码发送 REST 请求时,会忽略配置(不会JsonbDateConfig触发方法中的调试断点)。

Response response = target.path(REST_SERVICE_NAME)
  .request()
  .post(Entity.entity(dataTO, MediaType.APPLICATION_JSON));

因此,生成的 JSON 包含格式不正确的日期值。

我可以创建一个JsonbAdapter并将注释添加@JsonbTypeAdapter(DateAdapter.class)到 type 的字段java.util.Date。但是,我更喜欢适用于所有日期字段的解决方案。不工作的解决方案是什么ContextResolver

请注意,WildflyContextResolver在启动期间加载我的实现类(类加载断点),当我收到传入的 REST 请求时使用此解析器。

标签: jsonjax-rswildflyjsonbyasson

解决方案


由于您使用的是 JAX-RS 客户端,因此您需要向客户端注册提供程序。

Response response = target.path(REST_SERVICE_NAME)
  .register(JsonbDateConfig.class)
  .request()
  .post(Entity.entity(dataTO, MediaType.APPLICATION_JSON));

推荐阅读