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;
}
}
上面的代碼打?。?/p>
{
"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"}
添加回答
舉報