码迷,mamicode.com
首页 > 编程语言 > 详细

Java自定义方法转换前端提交的json字符串为JsonObject对象

时间:2017-07-18 13:32:39      阅读:127      评论:0      收藏:0      [点我收藏+]

标签: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对象

标签:servlet   string   控制器   rac   bsp   ret   ping   buffer   object   

原文地址:http://www.cnblogs.com/xvpindex/p/7199778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!