Java 8 LocalDate Jackson格式

Java 8 LocalDate Jackson格式,第1张

Java 8 LocalDate Jackson格式

我从来没有能够使用注释使它简单地工作。为了使其正常工作,我创建了一个

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。发生了什么事,我得到了一个
N​​oClassDefFound 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<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`



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5059195.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存