我想过滤掉响应中的某些字段。应当在将Java对象序列化为JSON之前进行过滤。 考虑:
public class Entity {
@JsonProperty("some_property")
String someProperty;
@JsonProperty("nested_entity")
@OneToMany(mappedBy = "entity", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
NestedEntity nestedEntity;
// other fields for eg fieldA, fieldB
}
API端点
get api/entity/{id}?fields=some_property,field_a
现在要问的是,在o / p中,我们应该只过滤出someProperty和fieldA。喜欢
{
"some_property": "foo",
"field_a": "bar"
}
但是由于这些是JSON字段而不是Java对象字段,所以我无法通过反射过滤或获取这些字段。有没有一种方法可以实现这一点,即基于json字段过滤Java对象?
仅供参考:序列化之前进行过滤的优势在于,除非需要这些字段,否则将保存惰性字段的DB调用
谢谢!
答案 0 :(得分:1)
根据使用@JsonFilter
的@robocode的建议,并且还支持空fields
或不添加任何过滤杰克逊配置的字段
@JsonFilter("entityFilter")
public class Entity {
@JsonProperty("some_property")
String someProperty;
// other fields for eg fieldA, fieldB
}
@Configuration
public class JacksonConfiguration {
public JacksonConfiguration(ObjectMapper objectMapper) {
objectMapper.setFilterProvider(new SimpleFilterProvider().setFailOnUnknownId(false));
}
}
public class FieldMapper {
@SneakyThrows
public static Dto getFilteredFields(Dto make, String fields[]) {
ObjectMapper objectMapper = new ObjectMapper();
if(ArrayUtils.isNotEmpty(fields)) {
FilterProvider filters = new SimpleFilterProvider().addFilter(
"entityFilter", SimpleBeanPropertyFilter.filterOutAllExcept(fields)
);
objectMapper.setFilterProvider(filters);
} else {
objectMapper.setFilterProvider(new SimpleFilterProvider().setFailOnUnknownId(false));
}
JsonNode j = objectMapper.readTree(objectMapper.writeValueAsString(make));
return objectMapper.convertValue(j, Dto.class);
}
}
// controller code to get the dto for api/entity/{id}?fields=some_property,field_a
Dto filteredFields = getFilteredFields(dto, fields);
return filteredFields