java-產生任意格式的json資料

來源:互聯網
上載者:User

標籤:mapping   hashmap   伺服器   net   result   int   hash   一個   odi   

最近研究java的東西。之前靠著自己的摸索,實現了把java對象轉成json格式的資料的功能,返回給前端。當時使用的是 JSONObject.fromObject(object) 方法把java對象換成json格式。也就是先有一個java實體類,例如叫User。然後從資料庫查出列表資料,也就是一個List,裡面的每一條資料都是一個User的實體物件。而如果前端需求變化,需要在當前這個介面中多返回一個欄位時,就需要修改這個User實體類,新增欄位。這樣一來,所有用到這個User實體類的介面的地方,介面返回的json資料裡都會有新增的這個欄位。後來發現可以用一下方法根據需要動態拼接需要的欄位。

 

1、demo
package com.lin.domain;import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class Test {      public static void main(String[] args) throws Exception {          JSONObject createJSONObject = createJSONObject();        System.out.println(createJSONObject);    }         // 建立JSONObject對象      private static JSONObject createJSONObject() {          JSONObject result = new JSONObject();          result.put("success", true);          result.put("totalCount", "30");                  JSONObject user1 = new JSONObject();          user1.put("id", "12");          user1.put("name", "張三");          user1.put("createTime", "2017-11-16 12:12:12");             JSONObject user2 = new JSONObject();          user2.put("id", "13");          user2.put("name", "李四");          user2.put("createTime", "2017-11-16 12:12:15");                 JSONObject department = new JSONObject();        department.put("id", 1);        department.put("name","技術部");                user1.put("department", department);        user2.put("department", department);                  // 返回一個JSONArray對象          JSONArray jsonArray = new JSONArray();                    jsonArray.add(0, user1);          jsonArray.add(1, user2);          result.element("data", jsonArray);                    return result;      } }

返回的json資料:

 

2、介面demo

以下是真實的java介面,從資料庫查詢資料

@ResponseBody    @RequestMapping(value="/getRoleMenuList.do", method=RequestMethod.GET)    public void getRoleMenuList(HttpServletRequest req, HttpServletResponse res, Integer roleId) throws IOException{        res.setHeader("Content-type", "application/json;charset=UTF-8");        res.setCharacterEncoding("UTF-8");        ResListData rld = new ResListData();                JSONObject result = new JSONObject();                try {            Map<String, Object> params1 = new HashMap<>();            params1.put("roleId", roleId);            params1.put("menuLevel", 1);            List<RoleJuri> fMenuList = rjService.getRoleMenuList2(params1);    //一級菜單            JSONArray firstList = new JSONArray();                         for(int i=0; i<fMenuList.size(); i++){                RoleJuri firstMenu = fMenuList.get(i);                JSONObject firstResult = new JSONObject();                firstResult.put("id", firstMenu.getId());                firstResult.put("name", firstMenu.getMenuName());                firstResult.put("url", firstMenu.getMenuUrl());                Map<String, Object> params2 = new HashMap<>();                params2.put("roleId", roleId);                params2.put("menuPId", firstMenu.getMenuId());                List<RoleJuri> sMenuList = rjService.getRoleMenuList2(params2);    //二級菜單                                JSONArray secondList = new JSONArray();                for(int j=0; j<sMenuList.size(); j++){                    RoleJuri secondMenu = sMenuList.get(j);                    JSONObject secondResult = new JSONObject();                    secondResult.put("id", secondMenu.getId());                    secondResult.put("name", secondMenu.getMenuName());                    secondResult.put("url", secondMenu.getMenuUrl());                    secondList.add(secondResult);                }                firstResult.put("children", secondList);                firstList.add(firstResult);            }            if(fMenuList.size() > 0){    //查詢到了一級菜單                result.put("success", 1);                result.put("data", firstList);            }else{    //未查詢到一級菜單                result.put("success", 0);                result.put("data", new Array());                result.put("error", "未擷取到菜單資料");            }        } catch (Exception e) {            result.put("success", 0);            result.put("data", new Array());            result.put("error", "伺服器運行錯誤");        }        res.getWriter().write(result.toString());    }

 

返回的json資料

 

java-產生任意格式的json資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.