我正在使用 jackson-annotations 2.4 和相关 jar 从 JSON 转换为 POJO。假设我的 json 中有如下结构:
person
{
name
{
firstName,
lastName
}
}
我将 POJO 定义为:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"name"})
class Person
{
private Name name;
@JsonProperty("name")
public Name getName()
{
return name;
}
@JsonProperty("name")
public void setName(Name name)
{
this.name = name;
}
}
假设我为 Name 定义了一个类似的 POJO。现在我的问题是 Person
中 Name
的 getter 是否可以返回 null 值或者它在幕后实例化?
我尝试在谷歌上搜索,但似乎 jackson 返回了不可为空字段的默认值,但没有提及结构会发生什么?
最佳答案
这取决于你用来解析的 json,即:
{
"name": {
"firstname": "abc",
"lastname": "xyz"
}
}
或
{
"name": {
}
}
上面的两个 JSON 都不会为 person.getName()
返回 null,即使节点内的字段丢失。但另一方面,如果您没有在 json 中传递节点 name
,则 person.getName()
将始终返回 null。例如,此 JSON 将始终导致 person.getName()
为 null:
{
"name": "abc"
}
关于java - Jackson中JSON结构对应的POJO可以为null吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36290709/