4

我正在使用 Jersey 和 Jackson2 编写 Jax-RS 应用程序以促进 JSON i/o。该服务本身运行良好,但我想通过让杰克逊映射器自动序列化/反序列化日期和日期时间到 JodaTime 对象来改进它。

我正在关注此处的文档并添加了相关的罐子,但我迷失了这条指令:

Registering module

To use Joda datatypes with Jackson, you will first need to register the module first (same as with all Jackson datatype modules):

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

我尝试在扩展 jax.ws.rs.core.Application 的自定义类中执行此操作,但我对该解决方案完全没有信心。我目前收到此错误:

Can not instantiate value of type [simple type, class org.joda.time.DateTime] from String value ('2014-10-22'); no single-String constructor/factory method
 at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@3471b6d5; line: 7, column: 25]

除了这个模块注册需要在应用程序(servlet?)启动时发生的一般印象之外,我不知道如何处理这些信息。我是否需要用一些特别的东西来注释自定义类才能将其拾取?我应该扩展一些课程吗?

我在 StackOverflow 上找到的示例通常将其粘贴main()并直接调用映射器,但我依赖于 Jackson Databinding,因此这些示例不相关。任何方向表示赞赏。

4

1 回答 1

5

您基本上需要ObjectMapperContextResolver. 就像是

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {

    final ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperContextResolver() {
        mapper.registerModule(new JodaModule());
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }  
}

如果您正在使用包扫描来发现您的资源,那么@Provider注释应该允许这个类也被发现和注册。

基本上会发生什么, Jackson 提供的MessageBodyReaderMessageBodyWriter分别用于解组和编组,将调用 ,getContext中的方法ContextResolver来确定ObjectMapper要使用的。读取器/写入器将传入类(在读取器中,它将是方法参数中预期的类型,在写入器中,它将是作为响应返回的类型),这意味着我们可以使用不同的方式ObjectMapper为不同的类配置,如此处所示。在上述解决方案中,它用于所有类。

于 2015-04-09T00:53:46.707 回答