我正在尝试构建一个可以将对象序列化为JSON和XML的Web-Server。由于我已经集成了Jackson (使用一个示例-Project),所以我能够通过我的REST接口访问JSON序列化的对象,但我也想获得XML。
这..。
@Controller
@RequestMapping("/main/ajax")
public class AjaxController {
@RequestMapping(value = "/blah", method = RequestMethod.GET, headers = "Accept=application/xml")
public @ResponseBody List<String> blah(@RequestParam(value="input") String input){
List<String> stringList = new LinkedList<String>();
stringList.add("i");
stringList.add("am");
stringList.add("an");
stringList.add("json object");
stringList.add(input);
return stringList;
}
}点击此查询:
http://localhost:8080/spring-json/krams/main/ajax/blah?input=foobar生成该输出:
["i","am","an","json object","foobar"]有什么提示吗?
更新#1:我实现了ContentNegotiatingViewResolver...
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<!-- XML View -->
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
</constructor-arg>
</bean>
</list>
</property>
<property name="ignoreAcceptHeader" value="true" />
</bean>
<!-- If no extension matched, use JSP view -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>现在如何选择XML或JSON?localhost:8080/spring-json/sometestclass/status?localhost:8080/spring-json/sometestclass/status.xml?localhost:8080/spring-json/sometestclass/status.json?
上面的例子都不起作用,但是我可以用Accept-header "application/xml“或"application/json”强制响应格式...如果我执行以下操作...
@RequestMapping(value = "/status", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public @ResponseBody Web_ServerStatus isServerAlive() {
Web_ServerStatus l_ReturnObj = new Web_ServerStatus();...i只返回XML。
我遇到的问题是什么?
提前感谢!
发布于 2011-09-20 22:40:33
解决方案:
@RequestMapping(value = "/status", method = RequestMethod.GET)
public Web_ServerStatus isServerAlive() {
...
}没有"@ResponseBody“
发布于 2011-09-19 19:56:15
是的,看看ContentNegotiatingViewResolver (因为您将spring作为标记包括在内)。
这里有一个链接:http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-multiple-representations。
但是,REST并不意味着XML。根据客户端的Accept标头和服务的功能,您可以用不同的方式呈现资源。
https://stackoverflow.com/questions/7470388
复制相似问题