首页 > 解决方案 > Spring REST API - 如何正确格式化 XML 和 JSON 中的“列表”响应

问题描述

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

我尝试了什么:

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

下面是我正在尝试做的一个简化示例:

// 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>

任何帮助将不胜感激!

标签: javaspringspring-bootspring-mvcjackson

解决方案


推荐阅读