I hava a JAVA EE backend and I am using Spring MVC. I have a AJAX call like this:
function getAllProjects() {
$.getJSON(\"project/getall\", function(
You can also use org.json's JSONArray and JSONObject to construct the JSON output, then, return a String value as the @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();
}
You should get something like this in your ajax request's success callback.
[{
"id":"1",
"name":"My Test Project"
},{
"id":"4",
"name":"Another one"
}]
You can use this data to either append your ul li using javascript or using _underscore templating to render your UI.
You need to:
<mvc:annotation-driven>
to your configMap<Integer, String>
For more complex cases when you need to configure mapping process for each handler method you may use MappingJacksonJsonView
instead of @ResponseBody
, as Stepen C suggested.
The rest of these answers are extremely out-of-date! It's very easy now
@RestController
ex:
@RestController
public class MyController {
@RequestMapping("/thing")
public MyThing thing() {
return new MyThing();
}
}
ref: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-write-a-json-rest-service
As suggested here: Spring 3 JSON with MVC checkout this website: http://spring-json.sourceforge.net/ It has perfectly nice working example on how to do this in spring framework.
You need to read Chapter 15.5 of the Spring User Guide which describes how to configure MVC views, and Chapter 16.10 which briefly describes the JSON Mapping View. Then read the javadocs for MappingJacksonJsonView
etc.