对于java.util.Date当我做
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy") private Date dateOfBirth;
然后在发送JSON请求时
{ {"dateOfBirth":"01/01/2000"} }
有用。
我应如何针对Java 8的LocalDate字段执行此操作?
我尝试过
@JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) private LocalDate dateOfBirth;
没用
有人可以让我知道这样做的正确方法是什么。
以下是依赖项
<dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>jaxrs-api</artifactId> <version>3.0.9.Final</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>2.4.2</version> </dependency> <dependency> <groupId>com.wordnik</groupId> <artifactId>swagger-annotations</artifactId> <version>1.3.10</version> </dependency>
我从来没有能够使用注释使它简单地工作。为了使其正常工作,我创建了一个ContextResolverfor ObjectMapper,然后添加了JSR310Module(update:现在JavaTimeModule改为),以及另外一个警告,那就是需要将write-date-as-timestamp设置为false。有关更多信息,请参见JSR310模块的文档。这是我用过的一个例子。
ContextResolverfor ObjectMapper
JSR310Module
update
JavaTimeModule
write-date-as-timestamp
false
JSR310
相依性
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.4.0</version> </dependency>
注意:我遇到的一个问题是,jackson-annotation另一个依赖项引入的版本使用的版本为2.3.2,从而取消了所需的2.4 jsr310。发生了什么事,我得到了一个NoClassDefFound ObjectIdResolver,它是一个2.4类。所以我只需要排队包含的依赖版本
jackson-annotation
NoClassDefFound ObjectIdResolver
ContextResolver import 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; @Provider public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> { 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 Result: {“birthDate”:”2015-03-01”}
curl -v -POST -H “Content-Type:application/json” -d “{"birthDate":"2015-03-01"}” http://localhost:8080/api/person Result: 2015-03-01`