spring mvc rest response json and xml

Viewed 59937

I have the requirement to return the result from the database either as a string in xml-structure or as json-structure. I've got a solution, but I don't know, if this one is the best way to solve this. I have two methods here:

@RequestMapping(value = "/content/json/{ids}", method = RequestMethod.GET)
public ResponseEntity<String> getContentByIdsAsJSON(@PathVariable("ids") String ids)
{
  String content = null;
  StringBuilder builder = new StringBuilder();
  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.add("Content-Type", "text/html; charset=utf-8");
  // responseHeaders.add("Content-Type", "application/json; charset=utf-8");

  List<String> list = this.contentService.findContentByListingIdAsJSON(ids);
  if (list.isEmpty())
  {
     content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error>no data  found</error>";
     return new ResponseEntity<String>(content, responseHeaders, HttpStatus.CREATED);
  }
  for (String json : list)
  {
     builder.append(json + "\n");
  }
  content = builder.toString();
  return new ResponseEntity<String>(content, responseHeaders, HttpStatus.CREATED);
}

@RequestMapping(value = "/content/{ids}", method = RequestMethod.GET)
public ResponseEntity<String> getContentByIdsAsXML(@PathVariable("ids") String ids)
{
  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.add("Content-Type", "application/xml; charset=utf-8");

  String content = this.contentService.findContentByListingIdAsXML(ids);
  if (content == null)
  {
     content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error>no data found</error>";
     return new ResponseEntity<String>(content, responseHeaders, HttpStatus.CREATED);
  }
  return new ResponseEntity<String>(content, responseHeaders, HttpStatus.CREATED);
}

for the first method I need a better solution, which I already asked here: spring mvc rest mongo dbobject response

The next thing is, that I inserted in the configuration a json converter:

<bean id="jsonHttpMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
   <property name="supportedMediaTypes" value="application/json"/>
</bean>

when I change the content-type at the first method to "application/json", it works, but then the xml response doesn't work anymore, because the json converter wants to convert the xml string to json-structure I think.

what can I do, that spring identifies the difference that the one method should return a json type and the other one a normal xml as string? I tried it with the accept flag:

@RequestMapping(value = "/content/json/{ids}", method = RequestMethod.GET, headers = "Accept=application/json")

but this doesn't work. I get the following error:

org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.StackOverflowError

I hope that somebody can help me out.

7 Answers

After a lot research i think i have a good solution for this: very simple, spring by default, uses Jackson to working with Json, that library comes in the spring-boot-starter-web, but the Xml extention of Jackson doesn't come by default, all you need to do is import in your build.gradle or in your pom.xml the jackson-dataformat-xml dependency and now you can alternate between json or xml for example with a code like this:

@PostMapping(value = "/personjson")
public ResponseEntity<?> getJsonPerson (@RequestBody Person person) {
    return ResponseEntity.accepted().contentType(MediaType.APPLICATION_JSON)
    .body(person);
}

@PostMapping(value = "/personxml")
public ResponseEntity<?> getXmlPerson (@RequestBody Person person) {
    return ResponseEntity.accepted().contentType(MediaType.APPLICATION_XML)
    .body(person);
}

Where person is a bean (only have the @Component tag), Lock at that both codes are equal only the MediaType is different and it works!!, isn't nesesary too add the "produces" and "consumes" atributes to the Mapping tag, because Spring, by default, can consume both Json and Xml, i did an example sending a Json and getting. xml, and sending xml getting a Json, only you need to specify in your postman or in curl when you do the request, the correct header of the body that you are sending either application/json or application/xml.

Note: this is only a way a todo this, JAXB and XmlRootElement, is other way to do it.

Related