如何动态地将json响应对象映射到实体? [英] how to dynamically map a json response object to an entity?
问题描述
我正在实现ng2,其中我的user.service.ts调用REST服务并返回json,如下所示:
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())
}
返回的对象如下:
{
"Id":"1"
"FirstName":"John"
"LastName":"Smith"
}
我需要将其转换为如下所示的ng2用户实体:
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);
我希望它使用反射或类似的动态技术,以便映射自动发生,而无需任何其他显式编码.在ng2中执行此操作的好方法是什么?
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?
推荐答案
基于注释,您似乎想避免在类中使用构造函数.好吧,这里的最简单"解决方案是使用Object.assign()
:
Based on comments, seems you want to avoid having constructor in your class. Well, the "simplest" solution here is to use Object.assign()
:
getUser(id: number): Promise<User> {
return this.http.get('http://localhost:4000/users/1')
.map(res => Object.assign(new User(), res.json()))
.toPromise()
}
现在您的数据是User
的实例.
Now your data is an instance of User
.
演示: http://plnkr.co/edit/Gzi6tjZzTizDhlMCD1y9?p=preview(检查控制台)
这篇关于如何动态地将json响应对象映射到实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!