Javascript 解析JSON时未调用数据对象构造函数
我从服务器获取一些数据,然后将其解析为TypeScript类。我正在尝试使用一些继承-每个类都需要能够报告其类型。 下面是它的工作原理: 这是基类Javascript 解析JSON时未调用数据对象构造函数,javascript,json,angular,typescript,Javascript,Json,Angular,Typescript,我从服务器获取一些数据,然后将其解析为TypeScript类。我正在尝试使用一些继承-每个类都需要能够报告其类型。 下面是它的工作原理: 这是基类 import { PageElementType } from './page-element-type' export class PageElement { pageElementType: PageElementType; constructor(aPageElementType: PageElementType) {
import { PageElementType } from './page-element-type'
export class PageElement {
pageElementType: PageElementType;
constructor(aPageElementType: PageElementType) {
this.pageElementType = aPageElementType;
}
}
这是一个派生类
import { PageElement } from './page-element.model'
import { PageElementType } from './page-element-type'
export class Metadata extends PageElement {
id: number;
body: string;
constructor(){
super(PageElementType.metadata);
}
}
下面是我调用的解析数据的服务函数
getExam(){
let exam = this.http.get('http://orangeberry.hopto.org/api/Exam/1')
.map((response:Response) => <Exam>response.json())
.do(data => console.log(data));
return exam;
}
getExam(){
让exam=this.http.get('http://orangeberry.hopto.org/api/Exam/1')
.map((response:response)=>response.json())
.do(数据=>console.log(数据));
复试;
}
好像我得到了一些普通的东西。我想要真正遵循类定义的有意义的函数对象。在我的案例中,实现这一点最简单、最直接的方法是什么?强制转换只是静态代码分析的提示,但在运行时没有任何效果 如果希望该值成为类的实例,则需要自己创建此类实例:
.map((response:Response) => new Exam(response.json()))
其中,
Exam
类的构造函数将JSON分解为其属性。您希望有一个Exam
的实例吗?是的。如果我的示例代码有误导性,那么很抱歉:类型功能是在其他类中实现的,而不是在考试本身中实现的。考试包含一个元数据对象数组。我明白了。谢谢我已经阅读了反序列化的4个选项,在这里指出:。最后一个选择对我来说似乎是最好的。我的TypeScript类中的变量名与json字段匹配。对于我来说,是否有任何简单的方法可以将json解析为pojo,然后将值克隆到我的Typescript对象中?object.keys(json.map)(k=>this[k]=json[k])
如果json没有嵌套对象。事实上,我对这部分不太了解,因为我自己没有使用TypeScript。是的,嵌套对象会阻止这种“自动”方法。谢谢你,甘特!