簡體   English   中英

Jackson JSON:在過濾器中聲明的過濾器-如何忽略子過濾器?

[英]Jackson JSON: Filters declared within filters - how to ignore the child filter?

在過濾器中聲明過濾器時,出現異常。 例如,給定這些類(請注意,Parent具有Child成員):

@JsonFilter("Parent")
public class Parent {
    private String id;
    private String name;
    private Child child;
    private String other1;
    private String other2;
    // other fields
}

@JsonFilter("Child")
public class Child {
    private String id;
    private String name;
    // other fields
}

當我使用過濾器生成Child類的JSON時,我沒有問題。 但是當我使用過濾器以這種方式生成類Parent JSON時:

ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);

String[] ignorableFieldNames = { "other1", "other2" };

FilterProvider filters = new SimpleFilterProvider().
addFilter("Parent",SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

mapper.filteredWriter(filters).writeValueAsString(object);

我收到錯誤, No filter configured with id 'Child' 我了解,由於Child是在Parent中聲明的,並且都具有@JsonFilter批注,因此我收到錯誤消息,因為我僅使用了Parent過濾器。 但是我在兩個類中都需要注釋,因為我也僅在其他程序中的Child類上運行篩選器。 解決方法是什么?

答案是:您為每個帶注釋的過濾器將addFilter附加兩次或多次:

String[] ignorableFieldNames1 = { "other1", "other2" };
String[] ignorableFieldNames2 = { "other3", "other4" };

FilterProvider filters = new SimpleFilterProvider().     
addFilter("Parent",SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames1))
addFilter("Child",SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames2));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM