首页 > 解决方案 > 用双引号括起来的 POJO Json 对象不会反序列化为 Java

问题描述

我的应用程序正在从某个源接收 json 对象,这些对象被包装为字符串。这些不会被反序列化,但会抛出异常,如下所述。我创建了一个示例程序来重现这一点。有人可以指出是否有办法在反序列化或对象映射器配置以使其工作时忽略 json 字段周围的额外引号。

  @Test
  void testTrade() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    Trade trade = new Trade(2.3, "USD");
    String json = mapper.writeValueAsString(trade);
    System.out.println(json);
    Trade res = mapper.readerFor(Trade.class).readValue(json);
    Assertions.assertEquals(trade, res);

    String jsonString = "{\"value\":2.3,\"currency\":\"USD\"}";
    Trade res1 = mapper.readerFor(Trade.class).readValue(jsonString);

    String jsonString2 = "\"{\\\"value\\\":2.3,\\\"currency\\\":\\\"USD\\\"}\"";
    
    //This throws exception : Cannot construct instance of `com....Trade` (although at least one Creator exists):
    Trade res2 = mapper.readerFor(Trade.class).readValue(jsonString2);
  }
}

class Trade {
  double value;
  String currency;
  @JsonCreator
  public Trade(@JsonProperty("value") double value, @JsonProperty("currency") String currency) {
    this.value = value;
    this.currency = currency;
  }

//getters, equals, hashcode, toString()
}

例外:

    Cannot construct instance of `com....Trade` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"value":2.3,"currency":"USD"}')
 at [Source: (String)""{\"value\":2.3,\"currency\":\"USD\"}""; line: 1, column: 1]
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com....Trade` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"value":2.3,"currency":"USD"}')
 at [Source: (String)""{\"value\":2.3,\"currency\":\"USD\"}""; line: 1, column: 1]

标签: jsonjacksonjson-deserializationobjectmapper

解决方案


推荐阅读