Adr*_*ris 10 json typescript angular
如何使用TypeScipt解析复杂的json对象?
我有一个客户对象,他有一些发票.
这是我的模特:
export class Customer {
public id: string;
public name: string;
public invoices: CustomerInvoice[];
get invoicesCount(): number {
if (this.invoices== null) {
return 0;
}
return this.invoices.length;
}
constructor() {
}
}
export class CustomerInvoice {
public id: number;
constructor() {
}
}
Run Code Online (Sandbox Code Playgroud)
在我的服务中,我有:
ngOnInit() {
if (this.id != null) {
this.dataService.getCustomer(this.id).subscribe(data => {
this.customer = data;
},
err => console.log(err));
}
}
Run Code Online (Sandbox Code Playgroud)
客户数据很棒(我的客户ID,名称等都有一些值)但发票是空的.
json是正确的,data.Invoices.length返回一个数字.
如何使用TypeScipt解析复杂的json对象?
假设您的意思是将JSON解析为实际的类实例而不是简单的Javascript对象,TypeScript不会提供现成的此功能.
您可以创建使用接口声明中,你可以做一个类型断言(而不是类型- 投)在一定程度上模拟天生类型安全,如果在JSON是可信的,但仅此而已-我不知道原生工具序列化一个JSON实际用户定义类型的实例.
interface ICustomerInvoice {
id: number;
}
interface ICustomer {
id: string;
name: string;
invoices: ICustomerInvoice[];
}
var customer: ICustomer = JSON.parse(json) as ICustomer;
Run Code Online (Sandbox Code Playgroud)
然而,出于同样显而易见的原因,我开始将TypedJSON放在一起,将此功能引入TypeScript.您可以使用JsonObject和JsonMember装饰器注释您的类和成员:
@JsonObject
export class CustomerInvoice {
@JsonMember
public id: number;
}
@JsonObject
export class Customer {
@JsonMember
public id: string;
@JsonMember
public name: string;
@JsonMember({ elementType: CustomerInvoice })
public invoices: CustomerInvoice[];
get invoicesCount(): number {
if (this.invoices== null) {
return 0;
}
return this.invoices.length;
}
}
Run Code Online (Sandbox Code Playgroud)
要反序列化JSON字符串,您将使用TypedJSON.parse而不是JSON.parse,getter也将按预期显示:
var customer = TypedJSON.parse(json, Customer);
typeof customer.invoicesCount; // "number"
Run Code Online (Sandbox Code Playgroud)
这是推荐与使用ReflectDecorators(但不要求).如果您选择跳过此建议,则还需要为成员指定"类型"设置,例如:
@JsonMember({ type: String })
public id: string;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6556 次 |
| 最近记录: |