在实现接口过程当中,通常协议都是定义数据格式为json。咱们有时候须要把bean转换为JSON输出给接口调用者,可是可能存在bean中的字段有些不是接口定义所须要的。这个时候须要咱们对JSON转换是须要过滤掉不须要的字段。json-lib提供JsonConfig类给开发者,开发者只须要经过JsonConfig的setExcludes()和setJsonPropertyFilter()方法进行过滤没必要要的字段。
java
setExcludes()方法接受一个须要过滤的字段字符串数组,在该数组中的字段将被过滤掉。
json
/** * 生成指定要过滤的字段的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; }