HttpServletRequest获取json
时间: 2023-10-15 14:25:53 浏览: 102
HttpServletRequest获取JSON的方式有多种。其中一种常见的方法是通过获取POST请求的输入流,然后将输入流转换为字符流,并进行字符缓冲读取,拼接成字符串,最后使用JSON解析工具解析成JSON对象的形式。具体步骤如下:
1. 从HttpServletRequest中获取输入字节流:ServletInputStream requestInputStream = request.getInputStream();
2. 将字节流转换为字符流,并设置字符编码为UTF-8:InputStreamReader ir = new InputStreamReader(requestInputStream, "UTF-8");
3. 使用字符缓冲流进行读取:BufferedReader br = new BufferedReader(ir);
4. 开始拼装JSON字符串:String line = null; StringBuilder sb = new StringBuilder(); while((line = br.readLine()) != null) { sb.append(line); }
5. 使用JSON解析工具解析字符串为JSON对象:JSONObject json = JSONObject.parseObject(sb.toString());
6. 最后,你可以根据需要返回解析后的JSON对象或者继续进行其他操作。
总结起来,HttpServletRequest获取JSON的过程可以通过获取输入流,转换为字符流,进行字符缓冲读取,拼接成字符串,然后使用JSON解析工具进行解析。这样就可以获取到HttpServletRequest中的JSON数据了。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [HttpServletRequest--获取json数据](https://blog.csdn.net/qq_44691484/article/details/108266679)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [如何从Servlet中的HttpServletRequest参数中获取json](https://blog.csdn.net/theLuckyLong/article/details/125928025)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [使用easyui从servlet传递json数据到前端页面的两种方法](https://download.csdn.net/download/weixin_38670529/13653744)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文