java - “com.fasterxml.jackson.databind.JsonMappingException:预期类型为浮点数、整数或字符串。” 使用 ObjectMapper 转换 java.time.Instant
问题描述
我正在使用以下代码将linkedHashMap 映射到我的Custom Pojo 类。
ObjectMapper mapper = new ObjectMapper();**mapper.registerModule(new ParameterNamesModule()).registerModule(new Jdk8Module()).registerModule(new JavaTimeModule());** mapper.findAndRegisterModules(); mapper.convertValue(wrapper.getObject(), wrapper.getClassType());
这给了我以下异常“com.fasterxml.jackson.databind.JsonMappingException:预期类型浮点、整数或字符串”。
以前,它给了我一个不同的异常(com.fasterxml.jackson.databind.JsonMappingException:无法构造 java.time.Instant 的实例:找不到合适的构造函数,无法从 Object 值反序列化(缺少默认构造函数或创建者,或也许需要添加/启用类型信息?))并且在将突出显示的代码添加到映射器之后,它开始给出这个异常。谁能帮我弄清楚如何解决这个异常?
解决方案
我有以下测试适用于杰克逊 2.8.9。
public class FooTest {
public static class CustomBean implements Serializable {
private static final long serialVersionUID = 1L;
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public Instant time;
public String recordName;
public CustomBean() {
}
@Override
public String toString() {
return String.format("name:%s time:%s", recordName, time);
}
}
@Test
public void test_me() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();
Map<String, Object> data = new LinkedHashMap<>();
data.put("recordName", "test");
data.put("time", Instant.now());
String json = mapper.writeValueAsString(data);
System.out.println(json);
CustomBean bean = mapper.convertValue(data, CustomBean.class);
System.out.println(bean);
}
}
我得到的输出是:
{"recordName":"test","time":1536738977.085000000}
name:test time:2018-09-12T07:56:17.085Z
将此与评论中的 JSON 输出进行比较,感觉您的 Instant 未正确序列化。即使您正在加载,JavaTimeModule
所以我真的不知道为什么会这样。
推荐阅读
- apache-camel - 骆驼上下文在骆驼集群中如何工作?
- flutter - 您将如何根据选择的选项卡使用 DefaultTabController 显示不同的操作小部件?
- javascript - 将元素从一个数组移动到另一个数组以便可以重复(JavaScript)
- android - 如何只录制我自己的应用程序音频(不是其他应用程序或系统音频) - Android Studio
- node.js - Elasticsearch 没有生成唯一的 _id
- sql-server - 如何在 AWS 上恢复多部分 SQL Server 数据库备份?
- firebase - Google Firebase SAML 身份验证:出现 400 错误 INVALID_IDP_RESPONSE:没有断言
- python - 如何在列表列表中运行 for 循环以使用日期时间?
- mysql - 如何添加每天的“nemometro TS231 [m/s]”数据?
- css - 如何正确使用fontawesome