去除你臃肿的前端数据,不仅可以便于前端解析,并且可以减少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 }

 

@RestControllerpublic 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 ....