我使用 Spring 作为后端,Angular 作为前端。
这是我的 REST 代码:
@GetMapping(path = "/endpoint")
public @ResponseBody Iterable<Relations> getGraphGivenEndpointId(@RequestParam(value = "id") int id) {
return relationsRepository.findAllRelationsGivenEndpointId(id);
}
当我使用 Angular 调用它时,它返回以下 JSON:
0:
{ id: 27,
resourceUri:"http://datiopen.istat.it/odi/ontologia/microdati/musei/Visita",
endpoint: {id: 1, status: "ANALISI COMPLETATA", endpointUri: "http://datiopen.istat.it/sparql/musei"},
classStructure:{classUri:"http://datiopen.istat.it/odi/ontologia/microdati/musei/Visita",status: "ANALISI COMPLETATA",id: 6,endpoint: {id: 1, status: "ANALISI COMPLETATA", endpointUri: "http://datiopen.istat.it/sparql/musei"}},
predicateStructure:{id: 10, classStructure: classUri:"http://datiopen.istat.it/odi/ontologia/microdati/musei/Visita", status: "ANALISI COMPLETATA", id: 6, endpoint: {…}},
predicateUri: "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",status: "ANALISI COMPLETATA"}
}
但是我需要这个 JSON:
Edges[] = [
{
id: 'a',
source: '1',
target: '2',
label:'predicate'
}
];
Nodes[] = [
{
id: '1',
label: 'Node A'
},
{
id: '2',
label: 'Node B'
}
];
特别是我需要获取这个 JSON:
Edges[] = [
{
id: 'a',
source: '1',
target: '2',
label:'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
}
];
Nodes[] = [
{
id: '1',
label: 'http://datiopen.istat.it/odi/ontologia/microdati/musei/Visita'
},
{
id: '2',
label: 'http://datiopen.istat.it/odi/ontologia/microdati/musei/Visita'
}
];
Q1。这种JSON结构的更改最好在后端(Spring)或前端中进行>( Angular )?
Q2. 如何在 Spring 或 Angular 中更改 JSON 结构 ?
提前致谢。
最佳答案
我认为您需要的是 DTO(数据传输对象)的概念,您可以使用它以您需要的格式封装数据。
就我个人而言,我会在 Spring 后端执行此操作,通常我会在 Web 层( Controller )和数据存储库之间的应用程序中引入一个服务层,我建议您查看此模式.
这样您就可以灵活地定制发送回客户端(或多个客户端)的数据格式。
但是在您的实例和示例中,您可以执行以下操作
创建 DTO 对象,围绕您需要的响应结构建模,即
public class EdgeDto {
private String id;
private String source;
private String target;
private String label;
//Getters and Setters
}
public class NodeDto {
private String id;
private String label;
//Geters and Setters
}
public class RelationDto {
private List<EdgeDto> edges;
private List<NodeDto> nodes;
//Getters and Setters
}
然后在你的 Controller 中
@GetMapping(path = "/endpoint")
public @ResponseBody Iterable<RelationDto> getGraphGivenEndpointId(@RequestParam(value = "id") int id) {
Iterable<Relations> relations = relationsRepository.findAllRelationsGivenEndpointId(id);
Iternable<RelationDto> relationDtos = mapToRelationsDto(relations);
return relationDtos;
}
但是如上所述,您可能希望在 Controller 和数据库之间引入一项服务,这将为您提供更多控制权并更好地重用您可能需要的任何业务逻辑等。
关于java - 在 Spring 和 Angular 应用程序中更改 JSON 结构的位置和方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60206974/