我的RESTEasy JSON响应自定义问题。
在web.xml
我使用自动扫描:
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
这是ObjectMapper
的自定义类,
(我设置的不是空字段和新的人类可读日期):
@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:
@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会打印此日志:
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时,我收到了这个回复:(这里只是响应的一小部分)
{
"entry": [
{
"name": "abbigliamento",
"description": null,
"lastUpdate": 1375448941000,
"subCategory": null
},
{
"name": "car",
"description": null,
"lastUpdate": null,
"subCategory": null
}
}
我的服务器响应以毫秒为单位给出了空字段和lastUpdate
。
我哪里出错?
提前致谢。
答案 0 :(得分:4)
您可以通过扩展JacksonJsonProvider
来自定义Resteasy中的Jackson序列化。
@Provider
public class MyJacksonJsonProvider extends JacksonJsonProvider
{
@Override
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException
{
ObjectMapper mapper = locateMapper(type, mediaType);
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
mapper.setDateFormat(new SimpleDateFormat("dd.MM.yyyy"));
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
}
}
答案 1 :(得分:3)
感谢Greg Whitaker *,我找到了解决方案!
我不得不添加这种依赖
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>