使用Jackson ObjectMapper和Java 8可选值 [英] Using Jackson ObjectMapper with Java 8 Optional values

查看:354
本文介绍了使用Jackson ObjectMapper和Java 8可选值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Jackson将类值写入JSON,其中包含Optional作为字段:

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

这篇关于使用Jackson ObjectMapper和Java 8可选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆