![](/img/trans.png)
[英]Jackson ObjectMapper ignore all properties that has no annotation
[英]Jackson 2.0 ignore all properties on a class
我需要與@JsonIgnore
相反,我需要告訴Jackson忽略對象上的所有屬性,除了我注釋的對象。 我不小心想要有人添加屬性並忘記添加@JsonIgnore
然后我將它暴露在我不想要的地方。
誰知道如何實現這一目標?
實現類似功能的一種方法是使用SimpleBeanPropertyFilter
。 過濾器不能通過在您希望包含的字段上使用來解決問題,但它通過簡單地定義要序列化的字段來解決問題。
如果您假設以下POJO:
@JsonFilter("personFilter")
public class Person {
private final String firstName;
private final String lastName;
public Person(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getFullName() {
return getFirstName() + " " + getLastName();
}
public String getLastName() {
return lastName;
}
}
POJO有兩個我們不想序列化的屬性( firstName
和lastName
)。 我們只想序列化fullName
)。
您可能已經注意到,類頂部的@JsonFilter
注釋指向可以像這樣創建的命名過濾器:
// A filter that filter out all except for fullName
FilterProvider filters =
new SimpleFilterProvider().addFilter(
"personFilter",
SimpleBeanPropertyFilter.filterOutAllExcept("fullName"));
最后,您需要做的唯一事情是使用以下內容創建您的ObjectMapper
:
final ObjectMapper mapper = new ObjectMapper();
String json = mapper.writer(filters).writeValueAsString(new Person("Johnny", "Puma"));
該字符串將包含:
{“fullName”:“Johnny Puma”}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.