Java 如何使用 Jackson 定义可选的 json 字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19551098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:17:09  来源:igfitidea点击:

How to define optional json field using Hymanson

javajsonHymanson

提问by mkorszun

I have an object with one optional field and can not find proper annotation to model it. Any ideas what is the proper way to do it with Hymanson?

我有一个带有一个可选字段的对象,但找不到合适的注释来对其进行建模。任何想法与Hyman逊一起做的正确方法是什么?

采纳答案by mwhs

In Hymanson you cannot make the difference between optional and non-optional fields. Just declare any field in your POJO. If a field is not present in your JSON structure then Hymanson will not call the setter. You may keep track of wether a setter has been called with a flag in the POJO.

在 Hymanson 中,您无法区分可选字段和非可选字段。只需在您的 POJO 中声明任何字段。如果您的 JSON 结构中不存在字段,则 Hymanson 将不会调用 setter。您可以跟踪是否在 POJO 中使用标志调用了 setter。

回答by pyb

Coming late to the party...

聚会迟到了...

Using Hymanson 2.8.6 via Spring HttpMessageConverter 4.3.6, I had to change my setterparameter to the unwrapped type, like so:

通过 Spring HttpMessageConverter 4.3.6 使用 Hymanson 2.8.6,我不得不将我的 setter参数更改为解包类型,如下所示:

class Foo {
    private Optional<Bar> bar;

    public void setBar(Bar bar) { // NOT Optional<Bar>, this gives me Optional.empty()
        this.bar = Optional.of(bar);
    }

    // getter doesn't need to be changed
}