Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

JSON to Class Object in Angular

I have a model class with default values

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;
}

This builds up an object when I create an instance per : Person = new Person ();.

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

Now I have got JSON Model from server in the model

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

I want to fill the values to my class object but when I subscribe my class object with the result, it changes my class object to the form of JSON object and eliminating the default values giving me the Model that I received from server as the just above JSON. I get this form in per after I subscribe.

What I want is the JSON object must fill the class Object with the fields it matches and the unmatched fields must contain the default values.

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);
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to explicitely convert your Json object to the class you need.

You can do it in constructor:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...