Spring REST API - 如何在 XML 和 JSON 中正确格式化“列表”响应

5 java spring spring-mvc jackson spring-boot

我已经创建了一个 Spring Rest 控制器,并且我知道 Spring 在内部使用 Jackson 进行序列化/反序列化。但是,要求此 API 生成 XML 和 JSON。我注意到 jackson-dataformat-xml 对带有列表的 XML 进行了奇怪的序列化(请参见下面的示例)。然而,JSON 响应的格式正确。

我尝试过的:

  1. 我听说 JAX-RS 可以很轻松地处理 XML 和 JSON 中的这种格式。然而,我们使用 springdocs-openapi 来生成我们的 Swagger 文档,它似乎不支持 JAX-RS / Jersey。
  2. 围绕 DTO 创建一个仅包含类型字段的包装类List。这将修复 XML 格式,但会破坏 JSON 格式。

下面是我正在尝试做的事情的简化示例:

// Patient DTO
@XmlRootElement(name="patient")
public class Patient {
  private String firstName;
  private String lastName;
}
Run Code Online (Sandbox Code Playgroud)
// Controller 
@GetMapping(value = "/patients", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public List<Patient> getPatients() throws PatientNotFoundException {
  return patientService.getPatients();
}
Run Code Online (Sandbox Code Playgroud)
// JSON Response (this is the format we are getting and it is correct)
[
  {
     firstName: "John",
     lastName: "Smith"
  }
] 
Run Code Online (Sandbox Code Playgroud)
// 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>
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!