我从来没有能够使用注释使这个工作变得简单。为了让它工作,我创建了一个ContextResolverfor ObjectMapper,然后我添加了JSR310Module一个警告,这需要将write-date-as-timestamp设置为false。有关JSR310模块的文档,请参阅更多信息。这是我用过的一个例子。
依赖
com.fasterxml.jackson.datatype
jackson-datatype-jsr310
2.4.0
注意:我遇到的一个问题是jackson-annotation由另一个依赖项引入的版本,使用版本2.3.2,它取消了所需的2.4 jsr310。发生了什么事我得到了一个NoClassDefFound ObjectIdResolver,这是一个2.4级的。所以我只需要排列包含的依赖版本
ContextResolverimport com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;import com.fasterxml.jackson.datatype.jsr310.JSR310Module;import javax.ws.rs.ext.ContextResolver;import javax.ws.rs.ext.Provider;@Providerpublic class ObjectMapperContextResolver implements ContextResolver {
private final ObjectMapper MAPPER;
public ObjectMapperContextResolver() {
MAPPER = new ObjectMapper();
// Now you should use JavaTimeModule instead
MAPPER.registerModule(new JSR310Module());
MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
@Override
public ObjectMapper getContext(Class> type) {
return MAPPER;
} }
资源类@Path("person")public class LocalDateResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getPerson() {
Person person = new Person();
person.birthDate = LocalDate.now();
return Response.ok(person).build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createPerson(Person person) {
return Response.ok(
DateTimeFormatter.ISO_DATE.format(person.birthDate)).build();
}
public static class Person {
public LocalDate birthDate;
}}
测试curl -v http://localhost:8080/api/person
结果: {"birthDate":"2015-03-01"}
curl -v -POST -H "Content-Type:application/json" -d "{\"birthDate\":\"2015-03-01\"}" http://localhost:8080/api/person
结果: 2015-03-01
有关JAXB解决方案,另请参见此处。
UPDATE
JSR310Module自Jackson版本2.7起,该版本已被弃用。相反,您应该注册该模块JavaTimeModule。它仍然是相同的依赖。