添加JSON工具类
首先,要添加JSON的解析工具(这里选择阿里巴巴旗下的fastjson),可以是Jar包或者是Maven依赖的形式,这里我们用maven依赖来进行示范
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</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);
}
注意:本文归作者所有,未经作者允许,不得转载