[英]Make Ignore some of variable of the declared object when serializing to JSON?
我可能知道如何忽略聲明它的類中的某些成員變量。 例如,下面是3類,它們是PersonalInfo
和通過聲明AcedemicInfo
和FamilyInfo
。
public class PersonalInfo {
@JsonPropetry
private String name;
@JsonPropetry
String universityName;
@JsonPropetry
private String motherName;
@JsonPropetry
private String fatherName;
/* Set and Get*/
}
public class AcademicInfo {
@JsonPropetry
private PersonalInfo info; // need name and university only
/* Set and Get*/
}
public class FamilyInfo {
@JsonPropetry
private PersonalInfo info; // need name and fatherName and motherName only
/* Set and Get*/
}
但是,我需要忽略一些成員變量的PersonalInfo
作為AcedemicInfo
和FamilyInfo
並不需要所有的屬性PersonalInfo
。
以下是我想要的輸出
// Acedemic info json
{
"info" : {
"name":"Adam",
"universityName":"University"
}
}
// Family info json
{
"info" : {
"name":"Adam",
"fatherName":"Matt"
"motherName":"Jane"
}
}
我知道@JsonIgnore
,但是如果我將注釋放在PersonalInfo
類中,則聲明該變量的所有類都會忽略該變量,這不是我想要的。 我可以知道如何有條件地忽略該變量嗎? 對不起,我的英語不好。
一種方法是將@JsonFilter
與SimpleFilterProvider
和SimpleBeanPropertyFilter
以排除不進行序列化的屬性。
您的課程如下所示:
public class AcademicInfo {
@JsonFilter("academicPersonalInfoFilter")
private PersonalInfo info;
}
和序列化對象的示例:
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("academicPersonalInfoFilter",
SimpleBeanPropertyFilter.serializeAllExcept("motherName", "fatherName"));
ObjectMapper mapper = new ObjectMapper();
mapper.setFilters(filterProvider);
mapper.writeValueAsString(academicInfo);
另一種方法是使用多個@JsonView
定義一組要序列化的屬性。
您可以定義如下視圖:
public class Views {
public static class BasicPersonalInfo {
}
public static class AcademicPersonalInfo extends BasicPersonalInfo {
}
public static class FamilyPersonalInfo extends BasicPersonalInfo {
}
}
並在相應的視圖中注釋要序列化的字段:
public class PersonalInfo {
@JsonView(Views.BasicPersonalInfo.class)
private String name;
@JsonView(Views.AcademicPersonalInfo.class)
String universityName;
@JsonView(Views.FamilyPersonalInfo.class)
private String motherName;
@JsonView(Views.FamilyPersonalInfo.class)
private String fatherName;
}
並序列化對象,如下所示:
String result = mapper.writerWithView(Views.AcademicPersonalInfo.class)
.writeValueAsString(academicInfo);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.