json转换动态过滤字段

一、实现  

	/**
	 * 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相关的对象也可以自由的新增属性了,不用担心影响已经有了的接口。

 

 

转载于:https://my.oschina.net/fengshuzi/blog/751651

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值