I am using RESTEasy to implement a REST Service using JSON serialization. Currently, Dates are getting serialized to milliseconds since 1970. To improve compatibility, I would
Just annotate your fields with (note the string literal could be externalized/referred from a constant):
@javax.json.bind.annotation.JsonbDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
Date myDate;
Using with the JSR310 (new api date) - LocalDate, LocalDateTime, LocalTime
Add dependence:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.4.0</version>
</dependency>
And create a provider to register the module:
@Provider
public class JacksonConfig implements ContextResolver<ObjectMapper> {
private final ObjectMapper objectMapper;
public JacksonConfig() throws Exception {
objectMapper = new ObjectMapper()
.disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS )
.disable( SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS )
.setSerializationInclusion( JsonInclude.Include.NON_NULL )
.registerModule( new JSR310Module() );
}
@Override
public ObjectMapper getContext( Class<?> arg0 ) {
return objectMapper;
} }
You need to register your ContextResolver
implementation with Resteasy. You can do this by annotating your class with the @Provider
annotation and allowing Resteasy to automatically scan it during startup, registering it in web.xml, or registering it in a class that extends javax.ws.rs.core.Application
(if that is how you are bootstrapping Resteasy).
@Provider
public class JacksonConfig implements ContextResolver<ObjectMapper>
{
private final ObjectMapper objectMapper;
public JacksonConfig() throws Exception
{
objectMapper = new ObjectMapper.configure(
SerializationFeature.WRITE_DATE_AS_TIMESTAMPS, false);
}
@Override
public ObjectMapper getContext(Class<?> arg0)
{
return objectMapper;
}
}
Verify that classpath scanning is enabled in your web.xml file like so:
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
NOTE: If you are deploying this in JBoss 7 do not set the resteasy.scan
context parameter as it is enabled by default.
Add the following context parameter to your web.xml
file. The value of the parameter should be the fully qualified class name of your ContextResolver
.
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>foo.contextresolver.JacksonConfig</paramvalue>
</context-param>
If you are using an Application class to configure Resteasy you can add your provider to the set of services and providers to register with Resteasy like so:
public class MyApp extends Application
{
@Override
public Set<Class<?>> getClasses()
{
HashSet<Class<?>> set = new HashSet<Class<?>>(2);
set.add(JacksonConfig.class);
set.add(MyService.class);
return set;
}
}
More on standalone configuration HERE