Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 parsing JSON objects into angular classes [duplicate]

I've been following the Angular2 getting started documentation to get my own app off the ground, I've been successful in retrieving JSON objects from a local file and displaying them in angular2 templates. However currently it relies on the angular classes exactly matching the structure of the objects in my JSON file.

Eventually I'll need my app to work with JSON-LD, which has property names such as "@id". I've done some googling and it seems that RxJS might have the functionality I'm looking for but I'm not sure where to start to interupt the automatic binding from some JSON data straight into my angular2 classes, and instead be able to look up something that's labeled as "@id" in the json and set the value of SomeClass.id

Current code that automatically produces an array of a Person class:

getPeople(){
    return this._http.get(this._peopleUrl)
        .map(response => <Person[]> response.json().data)
        .do(data => console.log(data)) //debug to console
        .catch(this.handleError);
} 

Fine for JSON like this:

[
 {
  "id":"1",
  "name":"tessa"
 },
 {
  "id":"2",
  "name":"jacob"
 }
]

But it would obviously fail for JSON like this:

[
 {
  "@id":"1",
  "name":"tessa"
 },
 {
  "@id":"2",
  "name":"jacob"
 }
]

My class is simple (at the moment :-) )

export class Person {
  constructor(
    public id:number,
    public name:string,
  ){}
}

Can anyone point me in the right direction for some documentation/examples of mapping complex/tricky json to the classes in angular2?

like image 336
zanther Avatar asked Apr 06 '16 15:04

zanther


1 Answers

I found the answer in Option 4 of the answer given here: How do I initialize a typescript object with a JSON object

Hope this helps if anyone lands on this page looking for the same thing!

like image 75
zanther Avatar answered Nov 02 '22 00:11

zanther