在 RestEasy 中访问 Jackson 对象映射器 [英] Accessing Jackson Object Mapper in RestEasy

查看:46
本文介绍了在 RestEasy 中访问 Jackson 对象映射器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求美化来自 RestEasy 端点的默认 Jackson JSON.我对 Jackson 进行了一些研究,并编写了一些独立的代码,以便能够抑制空值、自定义数据格式等.现在的挑战是在 RestEasy 的 JSON 序列化中注入这些代码.

I've been asked to beautify default Jackson JSON coming out of a RestEasy endpoint. I did some research on Jackson and wrote some standalone code to be able to suppress nulls, customize data formats etc. Now the challenge is injecting this code in RestEasy's JSON serialization.

从论坛帖子来看,这在 Spring 中是微不足道的,但在 RestEasy 中似乎并非如此.我编写了一个 ContextResolver 并在 web.xml(在 Tomcat 上)的上下文参数中配置为 resteasy.provider,但这会阻止 webapp 在 Tomcat 上加载.

Judging from the forum posts this is trivial in Spring, however doesn't seem to be the case in RestEasy. I wrote a ContextResolver and configured as resteasy.provider in context params in web.xml (on Tomcat) but that prevents the webapp from loading on Tomcat.

现在我正在尝试扩展 javax.ws.rs.core.Application 并提供一个 ContextResolver 但没有任何进展.这是直接的吗,有人这样做过吗?非常感谢任何帮助.

Now I'm trying to extend javax.ws.rs.core.Application and provide a ContextResolver but making no progress. Is this straight forward, has anyone done this? Any help is greatly appreciated.

推荐答案

我找到了一种更好的修改 Jackson SerializationConfig 的方法 - 您可以使用 JAX-RS ContextResolver 拦截 ObjectMapper 创建.

I found a nicer way of modifying the Jackson SerializationConfig - you can intercept the ObjectMapper creation by using a JAX-RS ContextResolver.

@Provider
@Produces(Array(MediaType.APPLICATION_JSON))
class JacksonConfig extends ContextResolver[ObjectMapper] {

  val mapper = new ObjectMapper()
  mapper.getSerializationConfig.setSerializationInclusion(Inclusion.NON_NULL)

  def getContext(objectType: Class[_]) = mapper
}

您需要通过以下方式之一注册 RESTEasy:

You will need to register with RESTEasy in one of the following ways:

  • 将它作为类或实例从 javax.ws.rs.core.Application 实现返回
  • 使用 resteasy.providers 将其列为提供者
  • 让 RESTEasy 在您的 WAR 文件中自动扫描它.参见配置指南
  • 通过 ResteasyProviderFactory.getInstance().registerProvider(Class) 或 registerProviderInstance(Object) 手动添加

参考:RESTEasy 文档

参考:JBoss 论坛上的 Nicklas Karlsson

请注意,这适用于作为 JBoss 7.1.1.Final 中的模块提供的 RESTEasy 2.3.2,但似乎不适用于 RESTEasy 3.0-beta5.

Please note that this works with RESTEasy 2.3.2 which ships as a module in JBoss 7.1.1.Final, but does not appear to work with RESTEasy 3.0-beta5.

这篇关于在 RestEasy 中访问 Jackson 对象映射器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆