我正在JAX-RS 1.0下学习Jackson。服务器返回HTTP响应,如下所示:
{
"url": "http://localhost:8080/api/123",
"created": "2018-05-26T09:21:26.301+02:00"
}
我需要反序列化JSON响应到一个Java对象称为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;
}
}
在我的测试中,它未能构造ProductCreated
对象:
Product p = new Product("123", "foo");
ProductCreated c = wr.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(ProductCreated.class, p);
客户端错误是:
无法构造java的实例。时间ZoneDateTime
(不存在像默认构造那样的创建者):没有字符串参数构造函数/工厂方法从字符串值反序列化('2018-05-26T09:21:26.301 02:00'))
在服务器端,我配置了JSON映射器(但对我的测试没有影响,因为测试是客户端的?):
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);
}
我错过了什么?
完整的堆栈跟踪:
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
我能够用这段代码反序列化一个JSON文件,其中包含一个ZoneDateTime。
ObjectMapper objectMapper = new ObjectMapper()
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
objectMapper.registerModule(new JavaTimeModule())
MyObject myObject = objectMapper.readValue(new File("src/test/resources/data/my_object.json"), MyObject.class)
正如@PaulSamsotha指出的,我也需要在客户端注册JacksonJsonProvider:
ClientConfig cc = new DefaultClientConfig();
cc.getSingletons().add(ShopApplication.newJacksonJsonProvider());
wr = Client.create(cc).resource(Main.BASE_URI.resolve("products"));
其中包含定制的解决方案:
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);
}
问题内容: 我正在使用JAX-RS 1.0学习Jackson。服务器返回HTTP响应,如下所示: 并且我需要将JSON响应反序列化为Java对象: 在我的测试中,它无法构造对象: 客户端错误是: 无法构造(没有创建者,例如默认构造的实例)的实例:没有要从字符串值反序列化的字符串参数构造函数/工厂方法(‘2018-05-26T09:21:26.301 + 02:00’) 在服务器端,我配置了JSON
我正在使用Jackson,我遇到了问题,当我尝试反序列化一个对象时,我得到了以下错误: 我在属性上有问题: 有人能帮我吗?
问题内容: 默认构造函数到底是什么?你能告诉我以下哪个是默认构造函数,它与其他构造函数有何不同? 问题答案: 他们都不是。如果定义,则不是默认值。 除非你定义另一个构造函数,否则默认构造函数是自动生成的无参数构造函数。任何未初始化的字段都将设置为其默认值。对于你的榜样,它看起来像这样假设的类型String,int以及int,那类本身是公共的: 这与 完全没有构造函数。但是,如果定义至少一个构造函数
问题内容: 我知道我在这里问一些严重的101问题… 我有一些课,还有一个延伸课。在我有一个构造函数,它接受一组参数,并对其字段进行设置。派生类(例如)通常不需要进行修改。现在我的IDE给我 “ Foo中没有默认的构造函数” 。从一点点谷歌搜索,这似乎是因为“构造函数没有继承”。因此,一切都很好,但是我现在如何使它工作而不在每个派生类中复制此构造函数?我假设有一个更合理的方法? 问题答案: 使用构造
问题内容: 其实我不明白,无参数构造函数和默认构造函数有什么区别。 创建名为cFrame的Test对象时,这是否调用此类的默认构造函数? 问题答案: 该构造函数是一个无参数的构造函数,代表您的Java编译器插入; 它包含对(not )的调用,这是默认行为。如果实现任何构造函数,则不再收到默认的构造函数。 JLS-8.8.9。默认构造函数说(部分), 如果一个类不包含构造函数声明,则隐式声明一个没有
问题内容: 我正在尝试从Oracle网站[fxml教程](http://docs.oracle.com/javase/8/javafx/get-started- tutorial/fxml_tutorial.htm )上的JavaFX教程。 这是我不断得到的例外。该应用程序未显示在屏幕上。我从另一个堆栈溢出答案中完成了非args Main()构造函数,但没有解决。 问题答案: 缺少初始关键字。 也