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;
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;
John weisz
source share