我一直在使用codehaus和以下代码在序列化时从JSON中排除字段。
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(Object.class, PropertyFilterMixIn.class);
SimpleBeanPropertyFilter propertyFilter = SimpleBeanPropertyFilter.serializeAllExcept(ignoreFieldNames);
FilterProvider simpleFilterProvider = new SimpleFilterProvider().addFilter("PropertyFilter", propertyFilter);
ObjectWriter writer = mapper.writer(simpleFilterProvider);
String jsonContent = writer.writeValueAsString(obj);
我升级到fastxml并更改了代码,如下所示,
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(Object.class, PropertyFilterMixIn.class);
SimpleBeanPropertyFilter propertyFilter = SimpleBeanPropertyFilter.serializeAllExcept(ignoreFieldNames);
FilterProvider simpleFilterProvider = new SimpleFilterProvider().addFilter("PropertyFilter", propertyFilter);
//mapper.getSerializationConfig().withFilters(simpleFilterProvider);
ObjectWriter writer = mapper.writer(simpleFilterProvider);
String jsonContent = writer.writeValueAsString(obj);
但是,上面的代码没有按预期工作。它根本不尊重ignoreFieldNames,只返回对象中的所有字段(不排除“ignoreFieldNames”(String数组)中提到的字段。
非常感谢任何帮助。
提前致谢。
答案 0 :(得分:1)
您需要使用过滤器注释您的bean
@JsonFilter("PropertyFilter")
public class ClassImSerializing
或者如果您不能,可以将其添加为注释中的全局混合
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(Object.class, PropertyFilterMixIn.class);
@JsonFilter("PropertyFilter")
class PropertyFilterMixIn {
}