Spring-boot return json and xml from controllers

南笙酒味 提交于 2019-11-30 11:18:30

I had the exact same problem and I found the solution on Spring documentation website : here

In synthesis, I added the following dependency to the pom.xml of my project :

<dependency>
     <groupId>com.fasterxml.jackson.dataformat</groupId>
     <artifactId>jackson-dataformat-xml</artifactId>
 </dependency>

Then I added the following code block to the class that the service had to return :

 import javax.xml.bind.annotation.XmlRootElement;

 @XmlRootElement
 public class Greeting {...}

And it worked.

sonoerin

SOLUTION: I used a combination of both answers below (thank you very much!). I am posting here in case anyone else needs help.

My modified controller:

@Controller
public class RemoteSearchController {

    @Autowired
    private SdnSearchService sdnSearchService;

    @RequestMapping(value = "/remote/search", method = RequestMethod.GET, produces = { "application/xml", "text/xml" }, consumes = MediaType.ALL_VALUE )
    @ResponseBody
    public SdnSearchResults search(@ModelAttribute SdnSearch sdnSearch) {
        List<Sdn> foundSdns = sdnSearchService.find( sdnSearch );
        SdnSearchResults results = new SdnSearchResults();
        results.setSdns( foundSdns );
        return results;
    }
}

And on my client, I set the request headers:

Content-type: application/text Accept: text/xml I think ultimately the problem was that my client headers were not being set correctly, so I may not have had to make some of these changes. But I liked the idea of a SearchResults class containing a list of results:

@XmlRootElement
public class SdnSearchResults {
    private List<Sdn> sdns;
...
}

It may be better to create a new class:

public class SdnSearchResult {
  private List<Sdn> sdns;
  ...
}

Then, a slight change will be required to the existing classes as follows:

public interface SdnSearchService {
  SdnSearchResult find(SdnSearch sdnSearch);
}

@Controller
public class UISearchController {
  @Autowired
  private SdnSearchService sdnSearchService;

  @RequestMapping("/search")
  public ModelAndView search(@ModelAttribute SdnSearch sdnSearch) {
    return new ModelAndView("pages/search/results", "sdns", sdnSearchService.find(sdnSearch).getSdns());
  }
}

Once this is done, the other controller must be coded as:

@Controller
public class RemoteSearchController {
  @Autowired
  private SdnSearchService sdnSearchService;

  @RequestMapping("/remote/search")
  @ResponseBody
  public SdnSearchResult search(@RequestBody SdnSearch sdnSearch) {
    return sdnSearchService.find(sdnSearch);
  }
}

A quick explanation of the changes from your code:

  1. @RequestBody will automatically deserialize the entire HTTP request body to an SdnSearch instance. External applications will typically submit the request data as HTTP body, so @RequestBody will ensure that the deserialization to Java object happens automatically.
  2. @ResponseBody will automatically serialize the return value according to the external client's capabilities and the libraries available on the classpath. If Jackson is available on the classpath and the client has indicated that they can accept JSON, the return value will be automatically sent as JSON. If the JRE is 1.7 or higher (which means that JAXB is included with the JRE) and the client has indicated that they can accept XML, the return value will be automatically sent as XML.
  3. List<Sdn> needs to be changed to SdnSearchResult to ensure that the application can exchange JSON, XML, RSS and ATOM formats with a single controller method, since XML (and XML based formats) require a root-tag on the output, which a List<Sdn> cannot be translated to.

Once these changes are done, fire up a REST client such as the Postman extension for Chrome and submit a request to /remote/search with the following information:

  1. Request header Accepts set to application/json.
  2. Request header Content-Type set to application/json.
  3. Request body set to the JSON string { "sdnName" : "Victoria", "address" : "123 Maple Ave" }.

This will give you a JSON response.

You've marked the controller method as producing application/xml responses (produces = MediaType.APPLICATION_XML_VALUE). The request's accept header (Accept: text/xml) doesn't match so Spring determines that your search method cannot handle the request.

There are a few different ways to fix this on the server, depending on your exact requirements:

  • You could remove the produces attribute entirely
  • You could specify multiple media types: produces = { "application/xml", "text/xml" }

I am not sure about your version of Spring Boot (1.1.7.RELEASE) but I am on version 1.5.2.RELEASE and this xml conversion / serialization happens automatically without usage of any jackson dependencies as mentioned in few of the answers.

I guess that is happening because org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter is automatically configured since Spring Boot version 1.5.1.RELEASE & that converter uses default JAXB implementation of JRE ( so no explicit xml conversion dependency needed ) .

Second, Accept header set by clients in request decides which format the output is expected so a request mapping like below ( i.e. a single end point ) ,

@RequestMapping(method = RequestMethod.GET, value = "/remote/search", produces = {
        MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE })

can be used to produce an xml as well as a JSON response ( if Accept header is set as text/xml or application/xml & application/json respectively.

Note 1 : javax.xml.bind.annotation.XmlRootElement needs to be specified on root class if xml response is expected for a Java class. This is mandatory.

Note 2 : Jackson for json is already included in Spring Boot so that is not to be explicitly included for json outputs

Note 3 : Accept header - Output match off happens automatically by framework & developer doesn't have to code anything specific for that.

So in my opinion, if you only add XmlRootElement to your base class & upgrade your Spring Boot version, your server side is all set. Responsibility to set correct Accept header lies with the clients.

In addition to what Michael told in his answer, I added the following dependencies as well to pom.xml

<dependency>
    <groupId>org.codehaus.woodstox</groupId>
    <artifactId>woodstox-core-asl</artifactId>
    <version>4.4.1</version>
</dependency>

For some reason, the jackson-dataformat-xml alone was not helping. I also made sure that ResponseEntity is returned in the get call and removed the produces=MediaType from the RequestMapping annotation.

With these changes, I was able to get the correct data but I had to give the extension of mime type to the REST URL during get call. ie, specify explicitly like: http://localhost:8080/hello.xml or http://localhost:8080/hello.json in browser

In my case I wanted to return a formatted xml string and it was all combined into one line.

Adding produces = { "application/xml", "text/xml" } to the request mapping was enough to return the string as formatted XML (with indentation).

example:

@RequestMapping(method= RequestMethod.GET, value="/generate/{blabla}", produces = { "application/xml", "text/xml" })
public String getBlaBla(@PathVariable("param") String param) throws IOException {

}

Goodluck.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!