一、实现
/**
* api需严格按照约定进行编写,这里通过filterPropertyArray对字段进行控制
*
* @param product
* @param excludingPropertyArray 只转换指定的属性
*/
public ProductVo(String[] excludingPropertyArray,Product product) {
if (product == null) {
return;
}
ObjectMapper filterMapper = new ObjectMapper();
//Product 是在Product对象上的@JsonFilter注解的名称
FilterProvider filterProvider = new SimpleFilterProvider().addFilter("Product",
SimpleBeanPropertyFilter.filterOutAllExcept(excludingPropertyArray));
filterMapper.setFilters(filterProvider);
String jsonStr = "{}";
JsonResult jsonResult = null;
try {
jsonStr = filterMapper.writeValueAsString(product);
jsonResult = JsonUtil.formJson(jsonStr, JsonResult.class);
} catch (Exception e) {
logger.error("json转换失败");
}
if (product != null) {
this.id = MapUtils.getIntValue(jsonResult, "id");
this.name = MapUtils.getString(jsonResult, "name");
this.price = MapUtils.getString(jsonResult, "price");
}
}
/**
* api需严格按照约定进行编写,这里通过filterPropertyArray对字段进行控制
*
* @param product
* @param filterPropertyArray json转换的时候需要提出的属性
*/
public ProductVo(Product product, String... filterPropertyArray) {
if (product == null) {
return;
}
ObjectMapper filterMapper = new ObjectMapper();
//Product 是在Product对象上的@JsonFilter注解的名称
FilterProvider filterProvider = new SimpleFilterProvider().addFilter("Product",
SimpleBeanPropertyFilter.serializeAllExcept(filterPropertyArray));
filterMapper.setFilters(filterProvider);
String jsonStr = "{}";
JsonResult jsonResult = null;
try {
jsonStr = filterMapper.writeValueAsString(product);
jsonResult = JsonUtil.formJson(jsonStr, JsonResult.class);
} catch (Exception e) {
logger.error("json转换失败");
}
if (product != null) {
this.id = MapUtils.getIntValue(jsonResult, "id");
this.name = MapUtils.getString(jsonResult, "name");
this.price = MapUtils.getString(jsonResult, "price");
}
}
二、注意事项
springmvc如果使用的json转换如果也是同一个包的话,使用@jsonFilter注解会包objectMapper并没有指定filterProviter,所以这里用的是fastJson包。
三、动态过滤实现的好处
准确的定义API,不会返回无关字段,api相关的对象也可以自由的新增属性了,不用担心影响已经有了的接口。