[英]Spring MVC -> JSON response
我有一个JAVA EE后端,我正在使用Spring MVC。 我有一个像这样的AJAX调用:
function getAllProjects() {
$.getJSON("project/getall", function(allProjects) {
???
});
}
我的后端系统:
@RequestMapping(value="/getall", method=RequestMethod.GET)
public @ResponseBody ??? getAllProjects() {
???
}
我必须实施哪些内容才能实现? 在后端系统中,我从数据库中调用唯一的id和项目的名称,例如:
1 => My Test Project
4 => Another One
23 => One More Test
id和项目名称应返回到前端系统,因此我可以构建这种类型的HTML ul / li列表:
<ul>
<li><a href="/1">My Test Project</a></li>
<li><a href="/4">Another One</a></li>
<li><a href="/23">One More Test</a></li>
</ul>
有谁知道如何做到这一点?
你需要:
<mvc:annotation-driven>
到您的配置中 Map<Integer, String>
对于更复杂的情况,当您需要为每个处理程序方法配置映射过程时,您可以使用MappingJacksonJsonView
而不是@ResponseBody
,正如Stepen C建议的那样。
您还可以使用org.json的JSONArray和JSONObject来构造JSON输出,然后返回一个String值作为@ResponseBody。
http://www.json.org/javadoc/org/json/JSONObject.html
@RequestMapping(value="/getall", method=RequestMethod.GET)
public @ResponseBody String getAllProjects() {
...
JSONArray jsonItems = new JSONArray();
JSONObject jsonItem1 = new JSONObject();
jsonItem1.put("id", "1");
jsonItem1.put("name", "My Test Project");
JSONObject jsonItem2 = new JSONObject();
jsonItem2.put("id", "4");
jsonItem2.put("name", "Another one");
jsonItems.put(jsonItem1);
jsonItems.put(jsonItem2);
return jsonItems.toString();
}
你应该在你的ajax请求的成功回调中得到这样的东西。
[{
"id":"1",
"name":"My Test Project"
},{
"id":"4",
"name":"Another one"
}]
您可以使用此数据使用javascript附加您的文件或使用_underscore模板来呈现您的UI。
您需要阅读Spring用户指南的第15.5章,其中介绍了如何配置MVC视图,以及第16.10章,其中简要介绍了JSON映射视图。 然后阅读MappingJacksonJsonView
等的javadocs。
其余的答案都已经过时了! 现在很容易
@RestController
例如:
@RestController
public class MyController {
@RequestMapping("/thing")
public MyThing thing() {
return new MyThing();
}
}
参考: http : //docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-write-a-json-rest-service
正如这里建议的那样: 带有MVC的Spring 3 JSON结帐这个网站: http : //spring-json.sourceforge.net/它有一个非常好的工作示例,如何在spring框架中执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.