Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...