how to dynamically map a json response object to an entity?

Viewed 6596

I'm implementing ng2 where my user.service.ts calls a REST service and returns json like this:

getUser(id: number): Promise<User> {
    return this.http.get('http://localhost:4000/users/1')
        .toPromise()
        .then(response => response.json())
}

The returned object looks like this:

{
   "Id":"1"
   "FirstName":"John"
   "LastName":"Smith"
}

I need to convert this into my ng2 user entity which looks like this:

export class User 
{
    Id: number;
    FirstName: string;
    LastName: string;
}

I'd like to do this in the most generic way that I can leverage as a pattern. For example, something like:

var user = userResponse.map(User);

I'd like this to use reflection or similar dynamic technique so the mapping happens automatically without any additional explicit codng needed. What would be a good way to do this in ng2?

4 Answers
Related