我需要在@JsonIgnore
序列化对象时添加Jackson ObjectMapper
带注释的字段。我知道你可以让我从我的班级中删除@JsonIgnore
注释,但我需要它们在我的应用程序的某些部分是可忽略的。在我的应用程序的另一部分中,我需要在@JsonIgnore
字符串中包含json
个带注释的字段。
答案 0 :(得分:4)
您可以定义SimpleBeanPropertyFilter和FilterProvider。
首先使用自定义过滤器对您的类进行注释,如下所示:
@JsonFilter("firstFilter")
public class MyDtoWithFilter {
private String name;
private String anotherName;
private SecondDtoWithFilter dtoWith;
// get set ....
}
@JsonFilter("secondFilter")
public class SecondDtoWithFilter{
private long id;
private String secondName;
}
这就是你动态序列化对象的方法。
ObjectMapper mapper = new ObjectMapper();
// Field that not to be serialised.
SimpleBeanPropertyFilter firstFilter = SimpleBeanPropertyFilter.serializeAllExcept("anotherName");
SimpleBeanPropertyFilter secondFilter = SimpleBeanPropertyFilter.serializeAllExcept("secondName");
FilterProvider filters = new SimpleFilterProvider().addFilter("firstFilter", firstFilter).addFilter("secondFilter", secondFilter);
MyDtoWithFilter dtoObject = new MyDtoWithFilter();
String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject);
答案 1 :(得分:0)
我建议在您的特定映射发生时通过反射以编程方式删除和重新添加它们。
答案 2 :(得分:0)
这告诉我你有两个不同的模型,有一些共同的元素。我会重新检查你的模型。
答案 3 :(得分:0)
public class MainProgram {
@JsonFilter("nameRemoveFilter")
public static class User{
private String name;
private String age;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
FilterProvider filters = new SimpleFilterProvider().addFilter("nameRemoveFilter",
SimpleBeanPropertyFilter.filterOutAllExcept("name","age"));
// and then serialize using that filter provider:
User user = new User();
try {
String json = mapper.writer(filters).writeValueAsString(user);
System.out.println(json);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Works for Latest version of Jackson after 2.0