功能简介:
Java 从 HttpServletRequest 中获取前端传输过来的json数据
效果展示:
请求示例:
post: 127.0.0.1:8081/getRequestJson
{"messageHistory",[{"message":"123","time":"2023-03-22 10:00:00"}],"isContextChat":true}
代码示例:
@RequestMapping(value = "getRequestJson", method = RequestMethod.POST)
@ResponseBody
public String getRequestJson(HttpServletRequest request) throws IOException {
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String requestBody = buffer.toString();
System.out.println("--------> get request json is :" + requestBody);
return requestBody;
}
拓展:文章来源:https://www.toymoban.com/news/detail-654478.html
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@RequestMapping(value = "getRequestJson", method = RequestMethod.POST)
@ResponseBody
public String getRequestJson(HttpServletRequest request) throws IOException {
// 1. 从HttpServletRequest对象中获取输入流,并读取请求正文。
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String requestBody = buffer.toString();
// 2. 使用JSON库(如Jackson、Gson等)将字符串解析为JsonNode或任何其他适合你的数据结构。
ObjectMapper mapper = new ObjectMapper(); // Jackson JSON库示例
JsonNode jsonNode = mapper.readTree(requestBody); // 解析为JsonNode对象
// 3. 现在,你可以使用jsonNode对象来访问和操作JSON数据了。
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
// 遍历所有属性并打印它们的值:
Iterator<String> fieldNamesIter= jsonNode.fieldNames();
while (fieldNamesIter.hasNext()){
String fieldName=fieldNamesIter.next();
JsonNode fieldValue=jsonNode.get(fieldName);
System.out.println(fieldName+": "+fieldValue.asText());
}
System.out.println("--------> get request json is :" + requestBody);
return requestBody;
}
文章来源地址https://www.toymoban.com/news/detail-654478.html
到了这里,关于java 获取request中json数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!