Spring REST API - How to correctly format "List" Response in both XML & JSON

Viewed 265

I have create a Spring Rest Controller, and I'm aware Spring uses Jackson internally for serializing/deserializing. However, there's a requirement that this API produces both XML & JSON. I noticed that jackson-dataformat-xml does weird serialization to XML with lists (see example below). The JSON response however, is correctly formatted.

What I tried:

  1. I've heard JAX-RS can handle this formatting pretty easily in both XML and JSON. However, we use springdocs-openapi to generate our Swagger documentation, which doesn't seem to support JAX-RS / Jersey.
  2. Create a wrapper class around the DTO that just contains a field of type List. This will fix the XML format, but will break the JSON formatting.

Included below is a simplified example of what I am trying to do:

// Patient DTO
@XmlRootElement(name="patient")
public class Patient {
  private String firstName;
  private String lastName;
}
// Controller 
@GetMapping(value = "/patients", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public List<Patient> getPatients() throws PatientNotFoundException {
  return patientService.getPatients();
}
// JSON Response (this is the format we are getting and it is correct)
[
  {
     firstName: "John",
     lastName: "Smith"
  }
] 
// Actual XML (we don't want these elements to be called "ArrayList" and "item")
<ArrayList>
  <item>
    <firstName>John</firstName>
    <lastName>Smith></lastName>
  </item>
</ArrayList>

// Expected XML (what we want)
<patients>
  <patient>
    <firstName>John</firstName>
    <lastName>Smith</lastName>
  </patient>
</patients>

Any help would be greatly appreciated!

0 Answers
Related