问题描述
我在尝试设置@ResponseBody以返回集合时遇到问题。我在类路径中有JAXB jar,我没有设置任何ContentNegotiatingViewResolver。
I'm having a problem trying to set up @ResponseBody to return a collection. I have JAXB jars in the classpath and I didn't set up any ContentNegotiatingViewResolver.
这是我的简单对象: -
This is my simple object:-
@XmlRootElement(name = "test-object")
@XmlAccessorType(XmlAccessType.FIELD)
public class TestObject implements Serializable {
@XmlAttribute
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
我写了一个返回单个对象的简单测试。 ..这没有问题,我能够看到生成的XML: -
I wrote a simple test that returns a single object... this works without problem, and I'm able to see the generated XML:-
@RequestMapping(value = "one", method = RequestMethod.GET)
public @ResponseBody TestObject getSingleObject() {
TestObject obj = new TestObject();
obj.setId(1);
return obj;
}
我真正想要的是返回一个对象列表。阅读后,似乎这样做的方法是将列表放在地图中并返回地图: -
What I really want is to return a list of objects. After reading around, it seems like the way to do so is to place the list in a map and return the map:-
@RequestMapping(value = "all", method = RequestMethod.GET)
public @ResponseBody Map<String, ? extends Object> getAllObjects() {
TestObject obj1 = new TestObject();
obj1.setId(1);
TestObject obj2 = new TestObject();
obj2.setId(2);
List<TestObject> list = Arrays.asList(obj1, obj2);
return Collections.singletonMap("all-objects", list);
}
当我执行上述操作时,我收到错误406不可接受 。
When I execute the above, I'm getting "Error 406 Not Acceptable".
我在这里做错了什么?我正在Jetty 6.1上运行,如果这有所不同。
What did I do wrong here? I'm running on Jetty 6.1 if that makes a difference.
谢谢。
推荐答案
你需要在pom.xml中添加这两个依赖项!
You need these two dependencies added in the pom.xml!
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-lgpl</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.8.1</version>
</dependency>
这篇关于返回Map的Spring MVC @ResponseBody产生“Error 406 NOT ACCEPTABLE”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!