我很好奇 Jackson 注释 @JsonIgnoreProperties(ignoreUnknown=true) 和 @JsonInclude(Include.NON_EMPTY) 在类级别上有区别吗?一个只是另一个的更新版本吗?谢谢!
jackson docs声明:
ignoreUnknown Property that defines whether it is ok to just ignore any unrecognized properties during deserialization.
这和空属性一样吗?
最佳答案
简短的回答:
@JsonIgnoreProperties(ignoreUnknown=true)
仅适用于将 JSON 反序列化为 Java 对象 ( POJO
)。如果您的 POJO 不包含 JSON 包含的某些属性,它们将被忽略并且不会引发错误。 @JsonInclude(Include.NON_EMPTY)
用于将 POJO 序列化为 JSON,它说,跳过以下 POJO 属性:null or what is considered empty are not to be included. Definition of emptiness is data type-specific.
长答案:
@JsonInclude
它仅在序列化时使用。它表示,如果所讨论的属性(或所有属性)的值等于某个值(
null
、 empty
- 无论这意味着什么,或默认值),则该属性不会序列化。如果没有这个注解,属性值总是被序列化。注释有助于减少传输的属性数量(当接收端不存在属性默认值时,必须指定它)。
例子:
public class Person {
public String firstName = "Mark";
public String middleName;
public String lastName = "Watney";
}
ObjectMapper mapper = new ObjectMapper();
Person p = new Person();
System.out.println(mapper.writeValueAsString(p));
产生以下输出:
{"firstName":"Mark", "middleName":null, "lastName":"Watney"}
但如果
Person
用 @JsonInclude(Include.NON_EMPTY)
注释, middleName
从输出中省略,因为它的值为“空”(在本例中为 null
):@JsonInclude(Include.NON_EMPTY)
public static class Person {
[....]
}
控制台输出为:
{"firstName":"Mark", "lastName":"Watney"}
@JsonIgnoreProperties
用于忽略序列化和反序列化中的某些属性,而不管其值如何:
to prevent specified fields from being serialized or deserialized (i.e. not include in JSON output; or being set even if they were included):
@JsonIgnoreProperties({ "internalId", "secretKey" })
To ignore any unknown properties in JSON input without exception:
@JsonIgnoreProperties(ignoreUnknown=true)
如果 JSON 输入是:
{
"firstName": "Homer",
"middleName": "Jay",
"lastName": "Simpson"
}
类(class)是:
public class Person {
public String firstName;
public String lastName;
}
反序列化
mapper.readValue(json, Person.class)
将产生 UnrecognizedPropertyException
异常(exception):Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "middleName" .....
因为属性(property)
middleName
不属于 Person
类(class)。但是如果类
Person
用 @JsonIgnoreProperties(ignoreUnknown=true)
注释,在反序列化为 POJO 时将忽略未知属性(如 middleName
)。@JsonIgnoreProperties(ignoreUnknown=true)
public class person {
[...]
}
另一个常见用例是抑制敏感属性的序列化,例如密码:
@JsonIgnoreProperties("password")
public static class User {
public String login = "simpsonh";
public String password = "D00nut";
public String firstName = "Homer";
public String middleName = "Jay";
public String lastName = "Simpson";
}
现在,如果您序列化 User class ,则输出中将省略密码:
User u = new User();
System.out.println(mapper.writeValueAsString(u));
控制台输出:
{
"login":"simpsonh",
"firstName":"Homer",
"middleName":"Jay",
"lastName":"Simpson"
}
关于serialization - jackson 注释 : Difference Between JsonIgnoreProperties(ignoreUnknown=true) and JsonInclude(Include. NON_EMPTY),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39005703/