去除你臃腫的前端數(shù)據(jù),不僅可以便于前端解析唉铜,并且可以減少Android 和IOS 端的閃退次數(shù)窩台舱,并且前端更快的對接你的接口窩,這時候JsonView 的作用就來了潭流。
其實spring 對于這個需求竞惋。還是有幾種方案的。
- jsonIgnore 這種不便于拓展灰嫉,也就是無法滿足一些定制的json 返回字段拆宛。
- jsonView 可以多繼承,因此可以定制你的bean讼撒,不過寫的代碼就需要多點了浑厚。
下面我直接給出我參考的地址。并且寫下我的使用的心得根盒。 - 最實用的link
下面給出我實現(xiàn)的代碼钳幅。直接貼代碼了寫出關鍵點。包括3步炎滞。
- 創(chuàng)建viewManager 去管理你的JsonView敢艰。
- 在你的實體里面你需要輸出到前端的 加上JsonView 。(jsonView 可以多繼承的册赛,首頁你可以根據(jù)不同的接口返回不同的數(shù)據(jù)钠导。)
- 在你的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 ....