如何从Servlet中的HttpServletRequest参数中获取json

添加JSON工具类

首先,要添加JSON的解析工具(这里选择阿里巴巴旗下的fastjson),可以是Jar包或者是Maven依赖的形式,这里我们用maven依赖来进行示范

<dependency>
      <groupId>com.alibabagroupId>
      <artifactId>fastjsonartifactId>
      <version>1.2.79version>
dependency>

将解析的过程抽象成一个方法

public static JSONObject getJson(HttpServletRequest request){
       //从前端获取输入字节流
		ServletInputStream requestInputStream = request.getInputStream();
		//将字节流转换为字符流,并设置字符编码为utf-8
		InputStreamReader ir = new InputStreamReader(requestInputStream,"utf-8");
		//使用字符缓冲流进行读取
		BufferedReader br = new BufferedReader(ir);
		//开始拼装json字符串
		String line = null;
		StringBuilder sb = new StringBuilder();
		while((line = br.readLine())!=null) {
			sb.append(line);
		}
		
		JSONObject json = JSONObject.parseObject(sb.toString()); 
 
        return (JSONObject) JSONObject.parse(json);
    }

你可能感兴趣的:(servlet,json,java)