How to force spring's @ResponseBody to use xml

2019-07-27 10:36发布

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.AnnotationMethodHandlerAdapter - 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?

2条回答
The star\"
2楼-- · 2019-07-27 10:55

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.

查看更多
够拽才男人
3楼-- · 2019-07-27 10:55

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.

查看更多
登录 后发表回答