问题描述
我正在尝试使用 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 类成员设置默认值,以防它为空?
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"
而不是 null
.有没有做这种事情的注解?
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 映射时将默认值设置为空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!