json - 用双引号括起来的 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]
解决方案
推荐阅读
- ngrx - 已经定义的单一效果的 NGRX 整体效果
- javascript - 如果有一个选项,如何禁用选择下拉菜单?
- python - Spyder 上发生了什么
- vba - 与多个模块共享表单
- x86 - 读取比 int 13h 磁道上更多的扇区
- eclipse - Eclipse Modeling Framework - 我需要 Epsilon 的 UML ecore 文件吗?
- tensorflow - 具有多个输入和多个输出的 Keras 模型
- c# - 将字符串附加到 StringBuilder 对象时如何保留转义字符?
- jquery - 根据溢出宽度确定动画时间
- microsoft-graph-api - 尝试查询 Microsoft Graph 的 getActivitiesByInterval 路由时出现错误 500