Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC -> JSON response

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(allProjects) {
            ???
        });
    }

My backend system:

@RequestMapping(value="/getall", method=RequestMethod.GET)
public @ResponseBody ??? getAllProjects() {
    ???
}

What is the content I have to implement so it will work? In the backend system I have from a database call the unique id and the name of the project, for example:

1 => My Test Project
4 => Another One
23 => One More Test

The id and the project name should be returned to the frontend system, so I can build a HTML ul/li list in this kind:

<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>

Does anyone know how this can be done?

like image 467
Tim Avatar asked Nov 17 '10 10:11

Tim


People also ask

How do I return a response body in JSON?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.

How pass JSON object in post request in spring boot?

Send JSON Data in POST Spring provides a straightforward way to send JSON data via POST requests. The built-in @RequestBody annotation can automatically deserialize the JSON data encapsulated in the request body into a particular model object. In general, we don't have to parse the request body ourselves.


2 Answers

You need to:

  • Add Jackson JSON Mapper to the classpath
  • Add <mvc:annotation-driven> to your config
  • Return Map<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.

like image 129
axtavt Avatar answered Sep 22 '22 02:09

axtavt


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.

like image 30
Stephen C Avatar answered Sep 24 '22 02:09

Stephen C