zoukankan      html  css  js  c++  java
  • 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();
    }
    

    作者:小策一喋
    邮箱:xvpindex#qq.com
    出处:http://www.cnblogs.com/xvpindex/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如果觉得本文对您有益,欢迎点赞、欢迎探讨。本博客来源于互联网的资源,若侵犯到您的权利,请联系博主予以删除。

  • 相关阅读:
    821. 字符的最短距离
    1122. 数组的相对排序
    258. 各位相加
    C++常见问题之二#define使用中的陷阱
    python进阶二_基本数据类型与操作
    DirectX10一变换(三)
    Android中编译工具链的改动----LLVM份量的增加
    DirectX10一矩阵代数(二)
    DirectX10一向量代数(一)
    基于asp.net + easyui框架,一步步学习easyui-datagrid——实现添加、编辑、删除(三)
  • 原文地址:https://www.cnblogs.com/xvpindex/p/7199778.html
Copyright © 2011-2022 走看看