本文介绍了RESTEasy和ContextResolver< ObjectMapper>为杰克逊的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的自定义RESTEasy JSON响应有问题。

I have a problem with the customization of my RESTEasy JSON response.

web.xml 我使用autoscan:

In web.xml I use autoscan:

<context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>true</param-value>
</context-param>

这是我的 ObjectMapper 的自定义类,
(我设置的不是空字段和新的人类可读日期):

Here is my customization class for ObjectMapper,(I've set not null fields and new human readable date):

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JacksonConfig implements ContextResolver<ObjectMapper> {
    private Logger log = Logger.getLogger(PropertiesConfig.LOG_CATEGORY);
    private ObjectMapper objectMapper;  

    public JacksonConfig() throws Exception  {  

        objectMapper = new ObjectMapper();
        objectMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        objectMapper.setDateFormat(new SimpleDateFormat("dd.MM.yyyy"));  
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

    @Override
    public ObjectMapper getContext(Class<?> arg0) {
        return objectMapper;
    }  
}

这是我的servlet:

Here is my servlet:

@Path("/search")
public class Search extends ArtesAPI {

    @GET
    @Path("/")
    @Produces(MediaType.APPLICATION_JSON)
    public Response search(@Context HttpServletRequest request){
        RequestManager reqManager = new RequestManager(request);
        MyResponse response = reqManager.doSearchRequest();
        return Response.status(200).entity(response).build();
    }
}

当我部署到服务器时,RESTEasy打印此日志:

When I deploy to the server, RESTEasy prints this log:

10:43:44,320 INFO  [TomcatDeployment] deploy, ctxPath=/MyServer
10:43:44,544 INFO  [ConfigurationBootstrap] Adding scanned @Provider: myserver.servlets.JacksonConfig
10:43:44,545 INFO  [ConfigurationBootstrap] Adding scanned resource: myserver.servlets.Search

但是当我调用搜索API时,我会收到以下回复:(这里是响应的一小部分)

But when I call the search API, I receive this response: (here a little part of response)

{
"entry": [
    {
        "name": "abbigliamento",
        "description": null,
        "lastUpdate": 1375448941000,
        "subCategory": null
    },
    {
        "name": "car",
        "description": null,
        "lastUpdate": null,
        "subCategory": null
    }
}

我的服务器响应给了我空字段和 lastUpdate 以毫秒为单位。

My server response gives me null fields and lastUpdate in milliseconds.

我哪里出错?

提前致谢。

推荐答案

感谢Greg Whitaker *,我找到了解决方案!

thanks to Greg Whitaker*, i found the solution!

我不得不添加这个依赖

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-jaxrs</artifactId>
    <version>1.9.13</version>
</dependency>




  • 他的解决方案迫使我添加此依赖项。

  • 这篇关于RESTEasy和ContextResolver&lt; ObjectMapper&gt;为杰克逊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 23:39