RESTful处理JSON

 1 @RequestMapping(value = "/dblist", method = RequestMethod.GET)
 2 @ResponseBody
 3 public Map<String, String> getDBList(Model model, HttpServletRequest request, HttpServletResponse response) {
 4     Map<String, String> ret = Maps.newHashMap();
 5 
 6     try {
 7         List<String> dbList = this.leftTreeService.getDBList(request.getSession(false));
 8         StringBuilder sb = new StringBuilder();
 9         for (String dbName : dbList) {
10             sb.append(dbName).append(",");
11         }
12 
13         ret.put("dblist", sb.toString());
14     } catch (Throwable t) {
15         int statusCode = t instanceof BizException ? Consts.BIZ_ERROR_CODE
16                 : HttpStatus.ORDINAL_500_Internal_Server_Error;
17         response.setStatus(statusCode);
18     }
19     
20     return ret;
21 }    

   @ResponseBody,代表着该函数返回的值将会放到response中,如果是复杂形式,将会被解析为JSON;如果返回的是Map,那么前台直接可以通过类似于对象的方式来获取(因为后台返回的json字符串被前台直接解析为就是JSON对象):

1 function getDBList(){
2     $.getJSON("${ctx}/query/dblist",function(data){
3         alert(data.dblist);
4     });
5 }

   早期的时候,返回的是List<Map<String, String>>,这个时候,就需要data就是一个List,需要通过索引来进行获取:

1 function getDBList(){
2     $.getJSON("${ctx}/query/dblist",function(data){
3         alert(data[0].dblist);
4     });
5 }

 $.getJSON("${ctx}/query/db/" + dbname +"/table/"+ tablename + "/fields", function(data) {.. ...});等价于
$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

RESTful的风格,返回的都是json,处理的也都是JSON,所以,需要有些坑避免:
1. 接口文档要看明白,值是[]还是{},前者是list<Map<String,Object>,后者直接就是Map<String,Object>即可;
2. 要看明白返回值中是否string,integer等多个类型,那样设计接收和发送的Map都是<String,Object>类型,值类型不要写死为固定的类型。
原文地址:https://www.cnblogs.com/xiashiwendao/p/8470713.html