web-dev-qa-db-ja.com

`Java.time.ZonedDateTime`のインスタンスを構築できません(デフォルトの構築物のようなクリエーターは存在しません)

JAX-RS 1.0でジャクソンを学んでいます。サーバーは、次のように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.time.ZonedDateTimeのインスタンスを構築できません(デフォルトの構築物のような作成者は存在しません):文字列値からデシリアライズする文字列引数コンストラクタ/ファクトリメソッドはありません( '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
6
Mincong Huang

@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);
}
14
Mincong Huang