获取requset请求中的json数据

本文将简单介绍当请求参数全部放置在json中时,如何获取(requset.getparparameter无法拿到)

请求实例:
在这里插入图片描述
解决思路:用流读取,转化String,再转为json对象

public static String getPostString(HttpServletRequest request) {
    
    
		BufferedReader in = null;
		String parameters = "";
		try {
    
    
			in = new BufferedReader(new InputStreamReader(
					request.getInputStream(), "utf-8"));
			String ln;
			StringBuffer stringBuffer = new StringBuffer();
			while ((ln = in.readLine()) != null) {
    
    
				stringBuffer.append(ln);
				stringBuffer.append("\r\n");
			}
			parameters = stringBuffer.toString();
		} catch (UnsupportedEncodingException e) {
    
    
			e.printStackTrace();
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}
		return parameters;
	}

//	实际应用
String reqBody = getPostString(request);
if(reqBody != null && !reqBody.equals("")) {
    
    
	String reqBodyinfo= URLDecoder.decode(reqBody, HTTP.UTF_8);
	JSONObject jsonData = (JSONObject) JSONValue.parse(reqBodyinfo);
	String data = jsonData.get("data")+"";
	// 如果data还是个json的话,就需要再转一下
	JSONObject json_data = (JSONObject) JSONValue.parse(data);
	//	再取其中的信息
	int gameID = Integer.parseInt(json_data.get("gameID")+"");
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42258975/article/details/108521074