将 Jackson ObjectMapper 与 Java 8 可选值一起使用 [英] Using Jackson ObjectMapper with Java 8 Optional values
问题描述
我试图使用 Jackson 将一个类值写入具有 Optional 作为字段的 JSON:
I was trying to use Jackson to write a class value to JSON that has Optional as fields:
public class Test {
Optional<String> field = Optional.of("hello, world!");
public Optional<String> getField() {
return field;
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(new Test()));
}
}
执行时,该类生成以下输出:
When executed, this class generates the following output:
{"field":{"present":true}}
我了解包含的存在/不存在字段,并且可以在读取 JSON 数据时解决它,但是我无法避免可选的实际内容从未写入输出的事实.:(
I understand the present/not present field being included and could work around it when reading the JSON data, however I can't get around the fact that the actual content of the optional is never written to the output. :(
除了根本不使用 ObjectMapper 之外,还有其他解决方法吗?
Any workarounds here except not using ObjectMapper at all?
推荐答案
你可以使用 jackson-datatype-jdk8 描述为:
You could use jackson-datatype-jdk8 which is described as:
支持新的 JDK8 特定类型,例如 Optional
Support for new JDK8-specific types, such as Optional
为了做到这一点:
- 添加
com.fasterxml.jackson.datatype:jackson-datatype-jdk8
作为依赖 - 向您的对象映射器注册模块:
objectMapper.registerModule(new Jdk8Module());
这篇关于将 Jackson ObjectMapper 与 Java 8 可选值一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!