【问题标题】:Transform nested JSON-Array into objects of typescript classes将嵌套的 JSON-Array 转换为 typescript 类的对象
【发布时间】:2019-12-16 09:19:01
【问题描述】:

数据库中有两个实体“人”和“姓名”。这两个实体之间是多对多关系,具有“从”和“到”两个属性。


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

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

Person 的 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&lt;Person[]&gt;('//localhost:8080/person') 不会返回 Person 数组。

【问题讨论】:

  • 你试过使用 JSON.parse 吗?
  • 如果您可以更改 API 以返回 Person 对象列表,则最好。数组响应看起来不像一个人,因为它有一个名称数组。
  • 如果您的 person 类与返回的 JSON 匹配,那么它就是这样。 TS 类不会为您做任何映射,如果您需要,您可以编写一个映射器..

标签: json angular typescript spring-boot http


【解决方案1】:

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

例如

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))

【讨论】:

    【解决方案2】:
    this.getAll().subscribe((res) =>{ persons =<Name[]>JSON.parse(res);});
    

    您可以解析 JSON 并将其转换为名称数组

    【讨论】:

    • 角度 http 客户端会为您执行此操作。永远不需要自己调用 parse
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2017-06-08
    • 2017-10-02
    • 2016-09-14
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多