在RestEasy中访问Jackson Object Mapper [英] Accessing Jackson Object Mapper in RestEasy

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

问题描述

我被要求美化默认的Jackson JSON来自RestEasy端点。我做了一些关于杰克逊的研究并写了一些独立的代码,以便能够抑制空值,自定义数据格式等。现在的挑战是在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上)的上下文params中配置为resteasy.provider,但这阻止了在Tomcat上加载webapp。

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.

推荐答案

好的,我弄清楚了,我能够通过编写基于自定义JacksonJsonProvider来实现这一点在 Jackson FAQ:JAX-RS 上。代码如下:

Ok,I figured it out, I was able to do this by writing a custom JacksonJsonProvider based on the Jackson FAQ: JAX-RS.The code is as follows:

@Provider
public class QBOJacksonJsonProvider extends JacksonJsonProvider {
    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Override
    public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String,Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
        Log.info(getClass(), "In custom JSON provider");
        //get the Object Mapper
        ObjectMapper mapper = locateMapper(type, mediaType);
        // Suppress null properties in JSON output
        mapper.getSerializationConfig().setSerializationInclusion(org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion.NON_NULL);
        // Set human readable date format
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        mapper.getSerializationConfig().setDateFormat(sdf);

        super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
    }
}

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

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