java如何创建具有多个“级别”的spring引导API
我的问题很简单,但我真的不知道如何解决它
很抱歉,我甚至不知道这些“级别”实际上是如何命名的。儿童标签?另外,我对整个API REST和Spring Boot以及JPA都是相当新的,比如我目前正在做一个实习,我几乎要自己完成一些任务。但无论如何
我希望API作为响应返回的是:
<base>
<level1>
<info1>
<something1>{database data}</something1>
<something2>{database data}</something2>
</info1>
</level1>
<level2>
<info2>
<something3>{database data}</something3>
</info2>
</level2>
</base>
但现在,它返回的GET请求只包含以下XML:
<something1>{database data}</something1>
<something2>{database data}</something2>
<something3>{database data}</something3>
数据库数据来自我使用JPA获得的数据库中的一个表,something1、something2、something3实际上是表列
我用的是SpringBoot,JPA,Maven,Liquibase
我有什么办法可以达到我想要的吗?正在获取级别1,信息1。。。如果是,怎么做
这就是我获取XML的方式:
- 存储库为空,仅扩展JPA:
@Repository
public interface AggregationDocumentRepository
extends JpaRepository<AggregationDocumentEntity, Long> {
}
- 服务:
public List<AggregationDocumentEntity> getAllAggregationDocuments() {
return aggregationDocumentRepository.findAll();
}
- 控制员:
@GetMapping(value = "/aggregation", produces = {"application/json", "application/xml"})
public List<AggregationDocumentEntity> getAllAggregationDocuments() {
List<AggregationDocumentEntity> allAggregationDocuments =
aggregationDocumentService.getAllAggregationDocuments();
if (allAggregationDocuments.size() == 0) {
log.error(
"Cannot return the agreggation documents: there is no aggregation documents in the database.");
} else {
log.info("Returned all aggregation documents in the database.");
}
return allAggregationDocuments;
}
我还有一个实体,其中包含16个值的getter和setter,它们是数据库的16列
一切都很顺利。API响应只需要具有这些“级别”
先谢谢你
# 1 楼答案
因此,如果我理解正确,您只需要更改xml表示模型,我将使用Jackson依赖项来解决这个问题:
这是一个示例代码:
useWrapping=false的XML:
useWrapping=true的XML:
如果您在文档中看到,您可以让包装器显示或不显示级别并更改它们的名称,那么在您的情况下,您将通过JpaRepository将方法实现为XML并列出它们。但是,如果您禁用该功能,并使用相同的服务创建另一个包装器,您就可以实现这一点
# 2 楼答案
这不是API调用,这是来自API调用的响应
实际上,您的响应似乎返回了一个单个对象,其中包含所有这些属性:
你的困惑在于,不是返回单个对象,而是返回级别列表
最终,数据应该如何返回是个人品味的问题,也是你希望客户如何与之交互的问题,但这至少应该让你走上正确的轨道