使用Jackson进行映射时,将默认值设置为空字段 [英] Setting default values to null fields when mapping with Jackson

查看:609
本文介绍了使用Jackson进行映射时,将默认值设置为空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Jackson将一些JSON对象映射到Java对象。 JSON对象中的某些字段是必需的(我可以用 @NotNull 标记),有些是可选的。

I am trying to map some JSON objects to Java objects with Jackson. Some of the fields in the JSON object are mandatory(which I can mark with @NotNull) and some are optional.

与Jackson映射后,未在JSON对象中设置的所有字段在Java中都将具有空值。是否有类似于 @NotNull 的注释,可以告诉Jackson为Java类成员设置默认值,如果它为null?

After the mapping with Jackson, all the fields that are not set in the JSON object will have a null value in Java. Is there a similar annotation to @NotNull that can tell Jackson to set a default value to a Java class member, in case it is null?

编辑:
为了使问题更清楚,这里有一些代码示例。

To make the question more clear here is some code example.

Java对象:

class JavaObject {
    @NotNull
    public String notNullMember;

    @DefaultValue("Value")
    public String optionalMember;
}

JSON对象可以是:

The JSON object can be either:

{
    "notNullMember" : "notNull"
}

或:

{
    "notNullMember" : "notNull",
    "optionalMember" : "optional"
}

@DefaultValue 注释只是为了表明我的要求。这不是一个真正的注释。如果JSON对象与第一个示例中的相似,我希望 optionalMember 的值为Value而不是。是否有注释可以做这样的事情?

The @DefaultValue annotations is just to show what I am asking. It's not a real annotation. If the JSON object is like in the first example I want the value of the optionalMember to be "Value" and not null. Is there an annotation that does such a thing?

推荐答案

没有注释来设置默认值。

您只能在java类级别设置默认值:

There is no annotation to set default value.
You can set default value only on java class level:

public class JavaObject 
{
    public String notNullMember;

    public String optionalMember = "Value";
}

这篇关于使用Jackson进行映射时,将默认值设置为空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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