开发者

How to force spring's @ResponseBody to use xmlConvertor

开发者 https://www.devze.com 2023-04-02 23:48 出处:网络
When I return a single object from a controller like this, @ResponseBody public MyClass module(...) { ...

When I return a single object from a controller like this,

@ResponseBody 
public MyClass module(...) {
...
}

I get the xml output on the client and log shows like this,

2011-09-07 18:22:06,963 [qtp1409490836-27] DEBUG org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter - Written [com.domain.MyClass@4374820d] as "application/xhtml+xml" using [org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@b4e1f3]

But If I use a list like this,

@ResponseBody 
public List<MyClass> module(...) {
...
}

It uses jsonConvertor and returns the json output.

2011-09-07 18:38:31,026 [qtp420370595-26] DEBUG org.springframework.web.servlet.mvc.annotation.开发者_如何学JAVAAnnotationMethodHandlerAdapter - Written [[com.domain.MyClass@654309f0]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@14419f80]

The MyClass is annotated with jaxb. In jersey I could say

@Produces({ MediaType.APPLICATION_XML })

How do I force spring to use the xmlconverter always?


There is some bug that means you cannot return your class in a list. You need to create a new class to hold your list of objects and return that in the @ResponseBody. Something like this:

@RequestMapping(value = Constants.URL, method = RequestMethod.GET)
public @ResponseBody ListHolder getFoos(HttpServletResponse response) {
    response.setContentType("application/xml");         
    List<Foo> foos = getFoos(); 
    ListHolder listHolder = new ListHolder();
    listHolder.setFoos(foos);
    return listHolder;
}

Annotate your ListHolder class with @XmlRootElement and if your have the jaxb jar or Java 6 then it should work.


If Spring cant find a JSON convert it can't send JSON. Try to remove jackson.jar from the class path and it should default to XML through XStream for all request.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号