[英]Send and parse the JSON to spring controller?
假設,如果我有JSON
數據,
var json = {"name":"kite Player","age":"25","hobby":"footbal"}
我可以通過發送JSON
數據
var jsonData = JSON.Stringfy(json);
在JQueryAjax
,
data = jsonData ,
我可以解析彈簧控制器中的JSON數據,
public class TestController {
@RequestMapping(method = RequestMethod.POST, value = "personDetails.html")
public @ResponseBody Result math(@RequestBody final Persons persons) {
String name = person.getName();
String age = persons.getAge();
String hobby = persons.getHobby();
// Other process
}
}
如何在Spring controller
解析JSON
,如果我需要在JSON
發送多個人的詳細信息,比如
var json = [ {"name":"kite Player","age":"25","hobby":"footbal"},
{"name":"Steve","age":"40","hobby":"fishing"},
{"name":"Marker","age":"28","hobby":"cricket"}
]
希望我們的堆棧成員能夠提供一個很好的解
這應該工作:
@RequestMapping(method = RequestMethod.POST, value = "personDetails.html")
public @ResponseBody Result math(@RequestBody List<Persons> personList) { ... }
- 重復和增加的例子 -
我在本地進行了測試,它對我有用。 這是代碼片段:
public class TestController {
public static class Test {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@RequestMapping(value = "/debug/test1.json", method = RequestMethod.POST)
@ResponseBody
public Test[] testList1(@RequestBody Test[] test) {
return test;
}
@RequestMapping(value = "/debug/test2.json", method = RequestMethod.POST)
@ResponseBody
public List<Test> testList2(@RequestBody List<Test> test) {
return test;
}
}
以下是測試結果(我用curl測試過):
Request:
curl --header "Content-type: application/json" --header "Accept: application/json" --data '[{"name": "John"}, {"name": "Jack"}]' http://localhost:8080/app/debug/test1.json
Response:
[{"name":"John"},{"name":"Jack"}]
Request:
curl --header "Content-type: application/json" --header "Accept: application/json" --data '[{"name": "John"}, {"name": "Jack"}]' http://localhost:8080/app/debug/test2.json
Response:
[{"name":"John"},{"name":"Jack"}]
PS。 有些時候,當JSON請求到達控制器之前失敗時,很難在spring MVC中獲取任何調試信息。 要獲得調試信息,在某些情況下,您需要將spring MVC的調試級別設置為trace。 當我需要驗證JSON請求失敗的原因時,我通常會將其添加到我的log4j.properties中:
log4j.logger.org.springframework.web.servlet.mvc.method.annotation=TRACE
您可以在Json數組中的JsonObject中發送每個成員詳細信息,然后您可以遍歷數組並獲取各個JSON對象。 您可以查看JSON的文檔,了解獲取和設置數據的所有可用方法。
另外我建議你使用GSON(google -json)他們對內存友好。 :)
試試這個代碼
@RequestMapping(method = RequestMethod.POST, value = "personDetails.html")
public @ResponseBody Result math(@RequestBody List< Persons > persons) {
for (Persons person : persons) {
String name = person.getName();
String age = person.getAge();
String hobby = person.getHobby();
// Process the data
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.