我正在从服务器发送以下格式的json响应:
{id: Int, name: String, childJSON: String}并愿意将其映射到
export class Student{
constructor(public id: string,
public name: string,
public childJSON: ChildObject) {
}
export class ChildObject {
constructor(public class: number,
public age: number){}在执行response.json() as Student;时,我得到了{id:1, name: "sumit", childJSON: "{class: 5, age: 10}",即childJSON具有string类型,而不是ChildObject类型。基本上,字符串没有映射到我的子对象。这是实现它的正确方式吗?或者我需要从服务器发送子对象,而不仅仅是JSON字符串
发布于 2017-02-02 16:06:56
您需要在构造函数中手动地“重新水化”对象,而不能使用“参数属性”快捷方式(在构造函数中使用public自动将构造函数参数转换为类属性的技术)。
下面是我会怎么做:
export class Student{
constructor(options: {
id: string;
name: string;
childJSON: any;
}) {
// Now you have to instantiate the class properties one by one.
this.id = options.id;
this.name = options.name;
this.childJSON = new ChildObject(options.childJSON);
}
}然后实例化:
const student = new Student(studentJson);或者,如果您使用一个可观察对象来获取数据:
this.http.get(...).map(...).subscribe(studentJson =>
this.student = new Student(studentJson)
}这种解决方案更加灵活,因为您可以直接传递原始JSON对象进行实例化。在您的示例中,您必须编写如下内容:
// NOT GOOD: You must pass each property individually, in the right order...
const student = new Student(studentJson.id, studentJson.name,...);https://stackoverflow.com/questions/41996817
复制相似问题