java - Spring REST API - 如何正确格式化 XML 和 JSON 中的“列表”响应
问题描述
我已经创建了一个 Spring Rest Controller,并且我知道 Spring 在内部使用 Jackson 进行序列化/反序列化。但是,此 API 需要同时生成 XML 和 JSON。我注意到 jackson-dataformat-xml 对带有列表的 XML 进行了奇怪的序列化(参见下面的示例)。然而,JSON 响应的格式正确。
我尝试了什么:
- 我听说 JAX-RS 可以很容易地在 XML 和 JSON 中处理这种格式。但是,我们使用 springdocs-openapi 来生成我们的 Swagger 文档,它似乎不支持 JAX-RS / Jersey。
- 在 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>
任何帮助将不胜感激!
解决方案
推荐阅读
- c# - 如何删除excel中的重复值以在DataGrid视图中的Windows窗体应用程序中导入并保存在SQL中
- javascript - 如果我运行多个 puppeteer 实例,heroku 会崩溃吗?
- xml - 如何使用 Coldfusion 访问 XML 数据
- networking - 终端输出变得不可读
- google-cloud-platform - GCP中全局VPC有什么好处
- asp.net - 当页面存在底层错误时,WebClient 导致 500 错误
- java - 如何启用显示?
- r - 聚类防止在传单中的 CircleMarkers 上悬停
- r - 最大值和最小值距离太远时的缩放颜色问题
- javascript - 保存到本地存储