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

來源:互聯網
上載者:User

標籤:servlet   string   控制器   rac   bsp   ret   ping   buffer   object   

前端提交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();}

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.