Spring MVC的 - > JSON响应 [英] Spring MVC -> JSON response

查看:174
本文介绍了Spring MVC的 - > JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我哈瓦在Java EE后端,我使用Spring MVC的。我有一个AJAX调用是这样的:

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

什么是内容我要实现这样它是否行得通呢?在后端系统我已经从数据库调用的唯一ID和项目的名称,例如:

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

ID和项目名称应退还给前端系统,这样我就可以建立一个HTML UL /李名单在这样的:

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?

推荐答案

您需要:

  • 添加杰克逊JSON 的映射到classpath
  • 添加&LT; MVC:注解驱动&GT; 到配置
  • 返回地图&LT;整数,字符串&GT;
  • Add Jackson JSON Mapper to the classpath
  • Add <mvc:annotation-driven> to your config
  • Return Map<Integer, String>

对于更复杂的情况下,当您需要配置映射过程中您可以使用每个处理程序方法 MappingJacksonJsonView ,而不是 @ResponseBody ,因为StepenÇ建议。

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.

这篇关于Spring MVC的 - &GT; JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆