I made a simple project that makes use of JAX-RS (RESTfull service)
I have a JAX-RS (RESTfull service) webservice project that deploys to JBoss AS 6.1. resteasy integrated with JSON is provided by JBoss 6.1 AS by default. I wanted to change the date format of the default JSON resource.
I got some help from the Internet and added a class that extends JacksonJsonProvider
:
- Accessing Jackson Object Mapper in RestEasy
- Jersey + Jackson JSON date format serialization - how to change the format or use custom 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);
}
}
This works well until I added an empty beans.xml under WebContent/WEB-INF for CDI injection.
MyJacksonJsonProvider
doesn't get called and I still get the default JSON date format.
Even adding the following dependency under pom.xml did not help:
<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>
Does anyone have any idea why MyJacksonJsonProvider
is ignored if I have an empty beans.xml under "WebContent/WEB-INF" folder? Thanks a lot in advance!
FYI, this is the sample model class:
@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;
}
}
And this is the class that produces JSON resource:
@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;
}
}