将JSON发送并解析为弹簧控制器?
假设,如果我有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 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 testList2(@RequestBody List 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。 当我需要validationJSON请求失败的原因时,我通常会将其添加到我的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 } }