2 回答
TA贡献1796条经验 获得超4个赞
您需要编写自定义序列化程序并实现该逻辑。它可能如下所示:
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"
}
TA贡献1853条经验 获得超18个赞
这可以使用 Jackson 的Mixin功能来实现。它允许在运行时应用来自外部类的注释。通过指定相同的属性名称来完成匹配(也适用于 getter/setter 等方法名称)
这是根据问题(为简单起见将实例变量公开)的示例,请注意 mixin 类仅包含您要覆盖的属性。此外,它不需要初始化。
具有相同属性名称并添加注释的 mixin 类
public class ProfileIgnoreFirstLastName
{
@JsonIgnore
public String firstName;
@JsonIgnore
public String lastName;
}
使用 mixin 类的条件应用进行序列化:
public static String serializeProfile(Profile profile) throws IOException {
ObjectMapper mapper = new ObjectMapper();
if (profile.isNameSecret) {
mapper.addMixIn(Profile.class, ProfileIgnoreFirstLastName.class);
}
return mapper.writeValueAsString(profile);
}
测试方法
public static void main(String[] args) {
try {
Profile profile = new Profile();
profile.isNameSecret = false;
System.out.println(serializeProfile(profile));
profile.isNameSecret = true;
System.out.println(serializeProfile(profile));
} catch (Exception e) {
e.printStackTrace();
}
}
输出
{"firstName":"my first name","lastName":"my last name","nickName":"my nick name"}
{"nickName":"my nick name"}
添加回答
举报