杰克逊根据值忽略序列化字段 [英] Jackson ignore serializing field depending on value
问题描述
我知道是否可以忽略字段为空或为空,但是是否可以忽略字段,例如,如果它是一个字符串,并且包含某个子字符串?
如果您结合使用@JsonIgnore
和Converter
.
如果您假设以下Person
POJO:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Person {
private final String email;
private final String name;
public Person(final String name, final String email) {
this.name = name;
this.email = email;
}
// Will use special conversion before serializing
@JsonSerialize(converter = EmailConverter.class)
public String getEmail() {
return email;
}
// Will simply use default serialization
public String getName() {
return name;
}
}
在POJO中,您定义仅应包含非空值.此外,声明将特定的转换器用于email
属性.可以这样定义转换器:
public class EmailConverter extends StdConverter<String, String> {
@Override
public String convert(final String value) {
return Optional.ofNullable(value)
.filter(email -> email.length() > 0)
.filter(email -> email.contains("@"))
.orElse(null);
}
}
请注意,转换器使用Optional
,它是 Converter 和 @ JsonSerialize .>
I know it's possible to ignore fields if they are null or if they are empty, but is it possible to ignore a field, for example if it is a String, and contains a certain substring?
This is possible if you e.g. use a combination of @JsonIgnore
and a Converter
.
If you assume the following Person
POJO:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Person {
private final String email;
private final String name;
public Person(final String name, final String email) {
this.name = name;
this.email = email;
}
// Will use special conversion before serializing
@JsonSerialize(converter = EmailConverter.class)
public String getEmail() {
return email;
}
// Will simply use default serialization
public String getName() {
return name;
}
}
In the POJO you define that only non-empty values should be included. Furthermore, it is declared that a specific converter is to be used for the email
property. The converter can be defined like this:
public class EmailConverter extends StdConverter<String, String> {
@Override
public String convert(final String value) {
return Optional.ofNullable(value)
.filter(email -> email.length() > 0)
.filter(email -> email.contains("@"))
.orElse(null);
}
}
Note that the converter uses Optional
which is a java-8 feature but any validation code will do just fine. When null is returned it is simply skipped since it was declared that way in the Person
class.
For more info, check out the JavaDocs for Converter and @JsonSerialize.
这篇关于杰克逊根据值忽略序列化字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!