Angular中的JSON到类对象

时间:2018-02-01 07:49:58

标签: json angular typescript

我有一个默认值为

的模型类
export class Person {
    _index : string ="hello";
    _type : string;
    _id : string;
    _score : number;
    _source : Source = new Source();
}
export class Source {
    name : string;
    age : number = 0;
    salary : number;
    details : Details = new Details();
}

export class Details{
    year : number = 1997;
    education : Education = new Education;
}


export class Education{
    score:number = 98;
}

这在我创建实例per : Person = new Person ();时构建了一个对象。

{
"_index":"hello",
"_source":{
"age":0,
"details":{
"year":1997,
"education":{
"score":98
}
}
}

现在我已经从模型中的服务器获得了JSON模型

}
"_index":"person",
"_type":"single",
"_id":"AWCoCbZwiyu3OzMFZ_P9",
"_version":2,
"found":true,
"_source":{
"name":"sauravss",
"age":"21",
"salary":"50000"
}
}

我想将值填充到我的类对象中但是当我用结果订阅我的类对象时,它将我的类对象更改为JSON对象的形式并消除默认值,从而为我提供从服务器收到的模型正好在JSON之上。我订阅后,我在per收到此表单。

我想要的是JSON对象必须用它匹配的字段填充Object类,并且不匹配的字段必须包含默认值。

editPerson():void {
    const id : string = this.route.snapshot.paramMap.get('id');
    console.log(id);
    this.personService.getPerson(id).subscribe(person => {
      this.per = person;
    });
  }

  getPerson (id : string): Observable<Person> {
    const url = `${this.url}/${id}`;
    console.log(id);
    return this.http.get<Person>(url);
  }

2 个答案:

答案 0 :(得分:0)

您需要明确地将Json对象转换为您需要的类。

你可以在构造函数中执行:

export class Person() {
    // ...
    constructor(jsonString: string) {
        const jsonData = JSON.parse(jsonString);
        // do your assignment from jsonData
    }
}

答案 1 :(得分:0)

这是现在的工作。这将有助于谁是角色的新手。如果有更好的解决方案请[评论]。

export class Person {
    _index : string;
    _type : string;
    _id : string;
    _source : Source = new Source();

    constructor (res : Person){
        this._id = res._id;
        this._index = res._index;
        this._type = res._type;
        if(res._source){
            this._source.name = res._source.name;
            this._source.age = res._source.age;
            this._source.salary = res._source.salary;
            if(res._source.details){
                this._source.details.year = res._source.details.year;
                if(res._source.details.education){
                    this._source.details.education = res._source.details.education;
                }
            }
        }
    }
}
export class Source {
    name : string = '';
    age : number = 0;
    salary : number = 0;
    details : Details = new Details();
}

export class Details{
    year : number = 1997;
    education : Education = new Education;
}


export class Education{
    score:number = 98;
}