java.time不存在,无法构造`java.time.ZonedDateTime`的实例(不存在像默认构造那样的创建者)...

I'm learning Jackson under JAX-RS 1.0. The server returns a HTTP response as follows:

{

"url": "http://localhost:8080/api/123",

"created": "2018-05-26T09:21:26.301+02:00"

}

and I need to deserialize the JSON response into a Java object called ProductCreated:

public class ProductCreated {

@JsonProperty("created")

private final ZonedDateTime created;

@JsonProperty("url")

private final String url;

public ProductCreated(String url) {

this.url = url;

this.created = ZonedDateTime.now();

}

@JsonCreator

public ProductCreated(

@JsonProperty("url") String url,

@JsonProperty("created") ZonedDateTime created) {

this.url = url;

this.created = created;

}

public String getUrl() {

return url;

}

public ZonedDateTime getCreated() {

return created;

}

}

In my test, it failed to construct the ProductCreated object:

Product p = new Product("123", "foo");

ProductCreated c = wr.type(MediaType.APPLICATION_JSON)

.accept(MediaType.APPLICATION_JSON)

.post(ProductCreated.class, p);

And the client side error is:

Cannot construct instance of java.time.ZonedDateTime (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2018-05-26T09:21:26.301+02:00')

On the server side, I configured the JSON mapper (but no effect to my test since test is client side?):

private static JacksonJsonProvider newJacksonJsonProvider() {

ObjectMapper mapper =

new ObjectMapper()

.registerModule(new ParameterNamesModule())

.registerModule(new Jdk8Module())

.registerModule(new JavaTimeModule()); // new module, NOT JSR310Module

mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

mapper.setDateFormat(new StdDateFormat());

return new JacksonJsonProvider(mapper);

}

What am I missing here?

The full stack-trace:

objc[91369]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin/java (0x10fe224c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x11164e4e0). One of the two will be used. Which one is undefined.

May 26, 2018 9:48:29 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate

INFO: Initiating Jersey application, version 'Jersey: 1.19.4 05/24/2017 03:46 PM'

May 26, 2018 9:48:31 AM org.glassfish.grizzly.http.server.NetworkListener start

INFO: Started listener bound to [localhost:8080]

May 26, 2018 9:48:31 AM org.glassfish.grizzly.http.server.HttpServer start

INFO: [HttpServer] Started.

May 26, 2018 9:48:31 AM io.mincong.shop.rest.MyRequestFilter filter

INFO: filter

May 26, 2018 9:48:31 AM org.glassfish.grizzly.http.server.NetworkListener stop

INFO: Stopped listener bound to [localhost:8080]

com.sun.jersey.api.client.ClientHandlerException: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.ZonedDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2018-05-26T09:48:31.622+02:00')

at [Source: (sun.net.www.protocol.http.HttpURLConnection$HttpInputStream); line: 1, column: 50] (through reference chain: io.mincong.shop.rest.dto.ProductCreated["created"])

at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:644)

at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:586)

at com.sun.jersey.api.client.WebResource.handle(WebResource.java:686)

at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)

at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:570)

at io.mincong.shop.rest.ProductResourceIT.createProduct(ProductResourceIT.java:53)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.lang.reflect.Method.invoke(Method.java:498)

at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)

at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)

at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)

at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)

at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)

at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)

at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)

at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)

at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)

at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)

at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)

at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)

at org.junit.runners.ParentRunner.run(ParentRunner.java:363)

at org.junit.runner.JUnitCore.run(JUnitCore.java:137)

at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)

at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)

at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)

at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.ZonedDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2018-05-26T09:48:31.622+02:00')

at [Source: (sun.net.www.protocol.http.HttpURLConnection$HttpInputStream); line: 1, column: 50] (through reference chain: io.mincong.shop.rest.dto.ProductCreated["created"])

at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)

at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1451)

at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1027)

at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371)

at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323)

at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1366)

at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:171)

at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161)

at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:529)

at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeWithErrorWrapping(BeanDeserializer.java:528)

at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:417)

at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1280)

at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)

at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)

at com.fasterxml.jackson.databind.ObjectReader._bind(ObjectReader.java:1574)

at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:965)

at com.fasterxml.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:815)

at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:634)

... 29 more

解决方案

As @PaulSamsotha pointed out, I need to register the JacksonJsonProvider on the client side too:

ClientConfig cc = new DefaultClientConfig();

cc.getSingletons().add(ShopApplication.newJacksonJsonProvider());

wr = Client.create(cc).resource(Main.BASE_URI.resolve("products"));

which contains the customized solution:

private static JacksonJsonProvider newJacksonJsonProvider() {

ObjectMapper mapper =

new ObjectMapper()

.registerModule(new ParameterNamesModule())

.registerModule(new Jdk8Module())

.registerModule(new JavaTimeModule()); // new module, NOT JSR310Module

mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

mapper.setDateFormat(new StdDateFormat());

return new JacksonJsonProvider(mapper);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
廖雪峰 Java 教程 Java教程 Java快速入门 Java简介 安装JDK 第一个Java程序 Java代码助手 使用IDE 使用IDE练习插件 Java程序基础 Java程序基本结构 变量和数据类型 整数运算 浮点数运算 布尔运算 字符和字符串 数组类型 流程控制 输入和输出 if判断 switch多重选择 while循环 do while循环 for循环 break和continue 数组操作 遍历数组 数组排序 多维数组 命令行参数 面向对象编程 面向对象基础 方法 构造方法 方法重载 继承 多态 抽象类 接口 静态字段和静态方法 包 作用域 classpath和jar 模块 Java核心类 字符串和编码 StringBuilder StringJoiner 包装类型 JavaBean 枚举类 BigInteger BigDecimal 常用工具类 异常处理 Java的异常 捕获异常 抛出异常 自定义异常 使用断言 使用JDK Logging 使用Commons Logging 使用Log4j 使用SLF4J和Logback 反射 Class类 访问字段 调用方法 调用构造方法 获取继承关系 动态代理 注解 使用注解 定义注解 处理注解 泛型 什么是泛型 使用泛型 编写泛型 擦拭法 extends通配符 super通配符 泛型和反射 集合 Java集合简介 使用List 编写equals方法 使用Map 编写equals和hashCode 使用EnumMap 使用TreeMap 使用Properties 使用Set 使用Queue 使用PriorityQueue 使用Deque 使用Stack 使用Iterator 使用Collections IO File对象 InputStream OutputStream Filter模式 操作Zip 读取classpath资源 序列化 Reader Writer PrintStream和PrintWriter 日期与时间 基本概念 Date和Calendar LocalDateTime ZonedDateTime DateTimeFormatter Instant 最佳实践 单元测试 编写JUnit测试 使用Fixture 异常测试 条件测试 参数化测试

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值