Java自定義方法轉換前端提交的json字符串為JsonObject對象


前端提交json字符串格式數據,Java后端通過自定義方法接收json字符串數據並轉換為JsonObject對象,代碼如下放到RequestData.Java類中:

public static JSONObject getRequestJsonObj(HttpServletRequest request) {
    InputStreamReader reader = null;
    InputStream in = null;
    String requsetSb = "";
    StringBuffer sb = new StringBuffer();
    try {
        in = request.getInputStream();
        reader = new InputStreamReader(in, "UTF-8");
        char[] buffer = new char[1024];
        int len;
        while ((len = reader.read(buffer)) > 0) {
            sb.append(buffer, 0, len);
        }
        //System.out.println("請求信息:" + sb.toString());
        requsetSb = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    JSONObject jsobj = JSONObject.fromObject(requsetSb.toString());
    return jsobj;
}

public static Object getRequestJsonObj(HttpServletRequest request, Class clazz) {
    JSONObject jsonObject = getRequestJsonObj(request);
    Object obj = JSONObject.toBean(jsonObject, clazz);
    return obj;
}

控制器中調用:

@RequestMapping("/test")
public void test(HttpServletRequest request) {
    JSONObject obj = RequestData.getRequestJsonObj(request);
    String userNameId = obj.getString("userNameId");
}

如果有實體Bean對象,可以通過以下方法接收:

@RequestMapping("/test")
public void test(HttpServletRequest request) {
    User user = (User) RequestData.getRequestJsonObj(request, User.class);
    String userNameId = user.getUserNameId();
}

 


免責聲明!

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



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