将对象列表序列化为Json,使用Jackson& Spring的MVC [英] Serialize list of objects to Json, with Jackson & Spring-MVC
问题描述
我正在研究一个项目,我需要以json格式返回一个对象列表。我正在使用带有jackson库的Spring-mvc框架来进行序列化。
I'm working on a project in wich I need to return a list of objects in json format. I'm using Spring-mvc framework with jackson library in order to do the serialization.
我想要一个直接包含对象的json结构,而不是'name:array of对象'。
I want a json structure containing directly the objects, not a 'name:array of objects'.
这是我的简化代码:
@RequestMapping(method = RequestMethod.GET, value = "/clients")
public List getClients(
@RequestParam(value = "estat", required = false) String estat
throws Exception {
List<Clients> l = s.mdClients(estat);
return l;
}
你看到的这个返回l直接转到Jackson,而jackson将'l'转换为如下结构:
This "return l" that you see goes directly to Jackson, and jackson converts 'l' into an structure like:
{
"ClientsList": [
{
"x": "2",
"y": "5"
}
]}
问题是根ClientsList。我想得到这个没有root的输出:
The problem is the root "ClientsList". I want to get this ouput without root:
{
[
{
"x": "2",
"y": "5"
}
]}
那么,有人可以帮忙吗?提前谢谢!
So, anyone could help? thanks in advance!
推荐答案
我在控制器中使用@ResponseBody找到了@vacuum评论的解决方案(谢谢!):
I've found the solution using @ResponseBody in my controller as @vacuum commented (thanks!):
@RequestMapping(method = RequestMethod.GET, value = "/clients")
public @ResponseBody List getClients(
@RequestParam(value = "estat", required = false) String estat
throws Exception {
List<Clients> l = s.mdClients(estat);
return l;
}
我还需要更改输出转换方法,使用
I also needed to change my output-conversion method, using
<mvc:annotation-driven />
在我的servlet-context.xml中,为了使用jackson库进行列表的json转换。
in my servlet-context.xml, in order to use jackson library for the json conversion of my list.
现在输出:
[
{
"x": "2",
"y": "5"
}
]
这篇关于将对象列表序列化为Json,使用Jackson& Spring的MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!