[英]Jackson: How to only ignore a Json property when creating a response?
我的Spring
應用程序正在從S3
獲取String
,我需要將其轉換為JSON
,然后再轉換為 Person object。這一切都按預期工作。
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(s );
Person person = mapper.treeToValue(actualObj, Person.class);
if(person.getBalance()>0{
person.setInCredit(true);
}
// todo - how to not return balance?
我的Object如下:
import com.fasterxml.jackson.annotation.JsonProperty;
public class Person{
@JsonProperty("id")
private Integer id;
@JsonIgnore
@JsonProperty("balance")
private Integer balance;
@JsonProperty("inCredit")
private Boolean inCredit;
// other fields and setters etc
}
如上所示,我最初需要讀取余額以確定 inCredit 字段,但我想從 json 響應中排除余額。
如何確保字段余額從我的查詢中讀取正常,但不會在我的端點響應中再次返回?
注意 - 我嘗試添加 JsonIgnore 但這沒有用。
您可以使用如下代碼:
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY, value = "balance")
private Integer balance;
或者您可以僅在 getter 方法上添加 @JsonIgnore。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.