spring-JsonView-过滤你返回的数据

去除你臃肿的前端数据,不仅可以便于前端解析,并且可以减少Android 和IOS 端的闪退次数窝,并且前端更快的对接你的接口窝,这时候JsonView 的作用就来了。

其实spring 对于这个需求。还是有几种方案的。

  1. jsonIgnore 这种不便于拓展,也就是无法满足一些定制的json 返回字段。
  2. jsonView 可以多继承,因此可以定制你的bean,不过写的代码就需要多点了。
    下面我直接给出我参考的地址。并且写下我的使用的心得。
  3. 最实用的link

下面给出我实现的代码。直接贴代码了写出关键点。包括3步。

  1. 创建viewManager 去管理你的JsonView。
  2. 在你的实体里面你需要输出到前端的 加上JsonView 。(jsonView 可以多继承的,首页你可以根据不同的接口返回不同的数据。)
  3. 在你的controller 上打上JsonView 和 RestController 注解即可。
//下面定义一个管理jsonView 的ViewManager 去管理JsonView 。
public class ViewManager{

  public interface   Entity{};

  public interface   EntityWithOther{};

}
//如果我们需要在前端输出 name age 在另外一个接口输出 otherEntity 
public class Entity{

  private int id;

  @JsonView(Entity.class)
  private String name;

  @JsonView(Entity.class)
  private int age;

  @JsonView(EntityWithOther.class)
  private OtherEntity otherEntity;

//ignore  getter setter method 
}
@RestController
public class IndexController{
    @JsonView(Entity.class)
    @RequestMapping(value = "/getArea" ,method = RequestMethod.GET)
    public Object getAreaByCity(@RequestParam Integer cityId){ 
       return areaService.findAreaByCityId(cityId);
    }

  @JsonView(EntityWithOther.class)
    @RequestMapping(value = "/getOther" ,method = RequestMethod.GET)
    public Object getOther(@RequestParam Integer cityId){ 
       return areaService.getOther(cityId);
    }
}

curl your url ,you can see the result what you want ....



作者:Rick____
链接:https://www.jianshu.com/p/82691cb295e4
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值