java如何獲取request中json數(shù)據(jù)
更新時間:2023年08月24日 09:16:03 作者:王家五哥
這篇文章主要給大家介紹了關(guān)于java如何獲取request中json數(shù)據(jù)的相關(guān)資料,文中通過代碼示例以及圖文將獲取的方法介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用java具有一定的參考借鑒價值,需要的朋友可以參考下
功能簡介:
Java 從 HttpServletRequest 中獲取前端傳輸過來的json數(shù)據(jù)
效果展示:

請求示例:
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;
}拓展:
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或任何其他適合你的數(shù)據(jù)結(jié)構(gòu)。
ObjectMapper mapper = new ObjectMapper(); // Jackson JSON庫示例
JsonNode jsonNode = mapper.readTree(requestBody); // 解析為JsonNode對象
// 3. 現(xiàn)在,你可以使用jsonNode對象來訪問和操作JSON數(shù)據(jù)了。
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;
}總結(jié)
到此這篇關(guān)于java如何獲取request中json數(shù)據(jù)的文章就介紹到這了,更多相關(guān)java獲取request json數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java運行時環(huán)境之ClassLoader類加載機制詳解
這篇文章主要給大家介紹了關(guān)于Java運行時環(huán)境之ClassLoader類加載機制的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
Mybatis實戰(zhàn)教程之入門到精通(經(jīng)典)
MyBatis是支持普通SQL查詢,存儲過程和高級映射的優(yōu)秀持久層框架,通過本文給大家介紹Mybatis實戰(zhàn)教程之入門到精通,對mybatis實戰(zhàn)教程相關(guān)知識感興趣的朋友一起學(xué)習(xí)吧2016-01-01
關(guān)于@JsonProperty,@NotNull,@JsonIgnore的具體使用
這篇文章主要介紹了關(guān)于@JsonProperty,@NotNull,@JsonIgnore的具體使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08

