忽略基于另一个字段值的序列化字段 [英] Ignore Serialize field based on another field value
本文介绍了忽略基于另一个字段值的序列化字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的班级:
public class Profile {
private String firstName;
private String lastName;
private String nickName;
@JsonIgnore
private boolean isNameSecret;
}
当isNameSecret
的值为true
时,序列化对象时可以隐藏属性firstName
和lastName
吗?
when serialising the object is possible to hide the properties firstName
and lastName
if the value of isNameSecret
is true
?
推荐答案
您需要编写自定义序列化程序并实现该逻辑.可能如下所示:
You need to write custom serialiser and implement that logic. It could look like below:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.IOException;
public class ProfileApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(mapper.writeValueAsString(new Profile()));
}
}
class ProfileJsonSerialize extends JsonSerializer<Profile> {
@Override
public void serialize(Profile profile, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
if (!profile.isNameSecret()) {
gen.writeStringField("firstName", profile.getFirstName());
gen.writeStringField("lastName", profile.getLastName());
}
gen.writeStringField("nickName", profile.getNickName());
gen.writeEndObject();
}
}
@JsonSerialize(using = ProfileJsonSerialize.class)
class Profile {
private String firstName = "Rick";
private String lastName = "Sanchez";
private String nickName = "Pickle Rick";
private boolean isNameSecret = true;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public boolean isNameSecret() {
return isNameSecret;
}
public void setNameSecret(boolean nameSecret) {
isNameSecret = nameSecret;
}
}
上面的代码显示:
{
"nickName" : "Pickle Rick"
}
这篇关于忽略基于另一个字段值的序列化字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文