运用json-lib生成特定json

              在实现接口过程中,一般协议都是定义数据格式为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;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值