java-生成任意格式的json數據


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

 需要購買阿里雲產品和服務的,點擊此鏈接領取優惠券紅包,優惠購買哦,領取后一個月內有效: https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=fp9ccf07

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數據

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM