我做了一个使用JAX-RS(RESTfull服务)的简单项目
我有一个部署到JBoss AS 6.1的JAX-RS(RESTfull服务)webservice项目。默认情况下,JBoss 6.1 AS提供了与JSON集成的resteasy。我想更改默认JSON资源的日期格式。
我从互联网上得到了一些帮助,并添加了一个扩展JacksonJsonProvider
的课程:
@Provider
@Produces("application/json")
public class MyJacksonJsonProvider extends JacksonJsonProvider {
public static final String pattern = "YYYY-MM-dd'T'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 {
ObjectMapper mapper = locateMapper(type, mediaType);
// Set customized date format
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
mapper.getSerializationConfig().setDateFormat(sdf);
super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
}
}
这一点很有效,直到我在WebContent / WEB-INF下添加了一个空beans.xml用于CDI注入。
MyJacksonJsonProvider
没有被调用,我仍然获得默认的JSON日期格式。
即使在pom.xml下添加以下依赖项也无济于事:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-cdi</artifactId>
<version>2.2.1.GA</version>
</dependency>
如果我在“WebContent / WEB-INF”文件夹下有一个空的beans.xml,是否有人知道为什么忽略MyJacksonJsonProvider
?非常感谢提前!
仅供参考,这是样本模型类:
@XmlRootElement(name = "movie")
public class Movie {
String name;
String director;
int year;
Date date;
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
@XmlAttribute
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
@XmlElement
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
这是生成JSON资源的类:
@Path("/json/movie")
public class JSONService {
@GET
@Path("/get")
@Produces("application/json")
public Movie getMovieInJSON() {
Movie movie = new Movie();
movie.setName("Little flower");
movie.setDirector("Zhang Zheng");
movie.setYear(1979);
movie.setDate(new Date());
return movie;
}
}
答案 0 :(得分:1)
我相信我也遇到了这个问题。这是一个known issue (RESTEASY-555),如果你无法将Resteasy升级到&gt; = 2.3.3.Final,那就是告诉Weld将MyJacksonJsonProvider
排除在下面:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:weld="http://jboss.org/schema/weld/beans"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://docs.jboss.org/cdi/beans_1_0.xsd
http://jboss.org/schema/weld/beans http://jboss.org/schema/weld/beans_1_1.xsd">
<weld:scan>
<weld:exclude name="MyJacksonJsonProvider" />
</weld:scan>
</beans>