问题描述
在 Java 中,我需要序列化一个对象,该对象是 Map
当我将另一个地图(如 Map
代码:
public class App3 {
public static void main(String[] args) throws JsonProcessingException {
Map<String,Object> fields = Map.of(
"Key 1",new Date(),"Key2",Map.of("Key2_1",new Date()),"Key3",List.of(new Date())
);
MyContainer myContainer = new MyContainer(fields);
System.out.println(objectMapper().writeValueAsString(myContainer));
}
public static class MyContainer {
@JsonProperty("fields")
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
private Map<String,Object> fields;
public MyContainer(Map<String,Object> fields) {
this.fields = fields;
}
}
public static ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
objectMapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
objectMapper.setNodeFactory(JsonNodeFactory.withExactBigDecimals(true));
return objectMapper;
}
}
此代码生成 Json 如下:
{
"fields": {
"Key3": [
"java.util.ImmutableCollections$List12",[
1612354278585
]
],"Key 1": [
"java.util.Date",1612354278585
],"Key2": {
"@class": "java.util.ImmutableCollections$Map1","Key2_1": 1612354278585
}
}
}
如您所见,Key3 和 Key2 缺少“java.util.Date”类型信息,因为它们是来自嵌套映射和嵌套列表的值。
有没有办法将其序列化为 Json,以便为嵌套映射值提供类似于 Key 1 的类型信息。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)