我使用Spring作为后端,使用角作为前端。
这是我的REST代码:
@GetMapping(path = "/endpoint")
public @ResponseBody Iterable<Relations> getGraphGivenEndpointId(@RequestParam(value = "id") int id) {
return relationsRepository.findAllRelationsGivenEndpointId(id);
}当我使用角调用它时,它返回这个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)或前端(角)?
Q2. 如何才能在Spring或角E 221中完成JSON结构的更改
提前谢谢。
发布于 2020-02-13 12:04:25
我认为您需要的是DTO (数据传输对象)的概念,您可以使用它以所需的格式封装数据。
就我个人而言,我将在Spring后端执行此操作,通常我要做的是在web层(控制器)和数据存储库之间的应用程序中引入一个服务层,我建议您了解一下这种模式。
这样,您就可以灵活地裁剪发送回客户端(或多个客户端)的数据格式。
但是在您的实例和示例中,您可以执行以下操作
根据所需的响应结构创建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
}然后在你的控制器里
@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;
}但是,如上所述,您可能希望在控制器和数据库之间引入一个服务,这将为您提供更多的控制,并更好地重用您可能需要的任何业务逻辑等。
发布于 2020-02-13 12:33:44
我认为这里有几种可能性,都在后端,也就是创建JSON的后端,如果您在角度上处理,您不会改变JSON --您只是在修改接收数据的方式。
可能做DTO是最好的方式,但在我的经验是保持尽可能类似于您的领域,如果不是,将使它在未来更复杂的维护。
https://stackoverflow.com/questions/60206974
复制相似问题