将嵌套的JSON-Array转换为打字稿类的对象

时间:2019-08-08 15:46:14

标签: json angular typescript spring-boot http

数据库中有两个实体“ person”和“ name”。在这两个实体之间,具有两个属性“从”和“到”的多对多关系。


 Person              PersonName                   Name
----------          -------------               -----------
id: number          from: number                 id: number
                    to: number                   firstname: string
                                                 lastname: string

Spring-Boot后端将所有人员的json数组发送到Angular前端。

一个人的Json对象如下:

{
 id: 1, 
 names: [
    {
    from: 1733,
    to: 1735,
    name:  {
            id: 1,
            firstname: John,
            lastname: Doe
           }
    }, ...
]

我的Angular服务如下:

export class PersonService {

    constructor(private http: HttpClient) { }

    getAll(): Observable<any> {
        return this.http.get('//localhost:8080/person')
    };
}

我为实体和关系构建类。例如,看起来名称类如下:

export class Name {
    id: number;
    firstname: string;
    lastname: string;
}

如何将Json-Array转换为Typescript类的对象? 目标是getAll()返回类型为Person []的Observable。

this.http.get('//localhost:8080/person')更改为this.http.get<Person[]>('//localhost:8080/person')不会返回Person数组。

2 个答案:

答案 0 :(得分:0)

this.getAll().subscribe((res) =>{ persons =<Name[]>JSON.parse(res);});

您可以解析JSON并将其投射到名称数组

答案 1 :(得分:0)

您的订阅中可能只需要一个映射器(下面提供了一个示例映射器)。您可能需要更改映射器以适合您的用例。

例如

this.personService.getAll().subscribe(result => this.persons = this.mapper(result))

const result = {
 id: 1, 
 names: [
    {
    from: 1733,
    to: 1735,
    name:  {
            id: 1,
            firstname: "John",
            lastname: "Doe"
           }
    },
    {
    from: 1735,
    to: 1736,
    name:  {
            id: 2,
            firstname: "Joan",
            lastname: "Smith"
           }
    }
]
}

const mapper = (toMap) => 
  toMap.names.map(p=> p.name)
  
console.log(mapper(result))