在实现接口过程中,一般协议都是定义数据格式为json。我们有时候需要把bean转换为JSON输出给接口调用者,但是可能存在bean中的字段有些不是接口定义所需要的。这个时候需要我们对JSON转换是需要过滤掉不需要的字段。json-lib提供JsonConfig类给开发者,开发者只需要通过JsonConfig的setExcludes()和setJsonPropertyFilter()方法进行过滤不必要的字段。
指定过滤某些字段属性
setExcludes()方法接受一个需要过滤的字段字符串数组,在该数组中的字段将被过滤掉。
/**
* 生成指定要过滤的字段的json配置
* @param arrFields
* @return
*/
public static JsonConfig getExculudeJsonConfig(String[] arrFields){
JsonConfig jsonConfig = new JsonConfig();
/*过滤默认的key*/
jsonConfig.setIgnoreDefaultExcludes(false);
/*过滤自包含*/
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); if(arrFields != null && arrFields.length > 0){
jsonConfig.setExcludes(arrFields);
} return jsonConfig;
}
指定生成某些字段属性
setJsonPropertyFilter()方法支持传递一个实现PropertyFilter接口对象参数。PropertyFilter接口中必须实现apply()方法。以下实现指定哪些字段必须转换成JSON格式,除此之外都不转换。
/**
* 生成指定的字段的json配置
* @param properties
* @return
*/
public static JsonConfig getJsonPropertyFilter(final String[] properties){
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter(new PropertyFilter(){ @Override
public boolean apply(Object source, String name, Object value) {
if (ArrayUtils.contains(properties, name)) {
return false;
} else {
return true;
}
}
}); return jsonConfig;
}