Parse complex json objects with TypeScript

How can I parse a complex json object using TypeScipt?

I have a customer object that has some invoices.

This is my model:

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() { } } 

And in my ministry I:

 ngOnInit() { if (this.id != null) { this.dataService.getCustomer(this.id).subscribe(data => { this.customer = data; }, err => console.log(err)); } } 

Customer data is great (my customer ID, name, etc. have some meanings), but invoices are zero.

json is correct, data.Invoices.length returns a number.

+7
json angular typescript
source share
1 answer

How can I parse a complex json object using TypeScipt?

Assuming that you mean parsing JSON in actual instances of the class instead of simple Javascript objects, TypeScript does not send this function ready-made.

You can create an interface declaration using which you can make type-assertion (rather than type-casting) to imitate the security type somewhat if the JSON is trusted, but that it - I don’t know my own tools for serializing JSON for real instances of custom types.

 interface ICustomerInvoice { id: number; } interface ICustomer { id: string; name: string; invoices: ICustomerInvoice[]; } var customer: ICustomer = JSON.parse(json) as ICustomer; 

However, for the same obvious reasons, I started compiling TypedJSON to introduce this function in TypeScript. You can annotate your classes and participants using the JsonObject and JsonMember decorators:

 @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; } } 

To deserialize a JSON string, you must use TypedJSON.parse instead of JSON.parse, then the receiver will also be present as expected:

 var customer = TypedJSON.parse(json, Customer); typeof customer.invoicesCount; // "number" 

Recommended for use with ReflectDecorators (but not required). If you decide to skip this recommendation, you also need to specify the type parameter for members, for example:

 @JsonMember({ type: String }) public id: string; 
+8
source share

All Articles