2016-02-19 135 views
7

如何用TypeScipt解析複雜的json對象?用TypeScript解析複雜的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() { 
    } 
} 

而在我的服務,我有:

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

客戶數據是巨大的(我的客戶ID,姓名等有一定的值),但發票是空的。

json是正確的,data.Invoices.length返回一個數字。

+1

沒有足夠的詳細信息。 – dfsq

回答

8

如何解析複雜的JSON對象與TypeScipt?

假設你的意思JSON解析成實際的類實例,而不是簡單的JavaScript對象,打字稿不發貨此功能現成的,貨架

您可以使用,你可以做一個type-assertion(不是一個類型 - )在一定程度上模擬天生如果的JSON是可信的類型安全創建一個接口聲明,但僅此而已 - 我不知道原生工具將JSON序列化爲用戶定義類型的實際實例。

interface ICustomerInvoice { 
    id: number; 
} 

interface ICustomer { 
    id: string; 
    name: string; 
    invoices: ICustomerInvoice[]; 
} 

var customer: ICustomer = JSON.parse(json) as ICustomer; 

然而,出於同樣的原因很明顯,我開始組建TypedJSON引入此功能爲打字稿。您可以使用的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; 
    } 
} 

反序列化的JSON字符串,你可以使用TypedJSON.parse代替JSON.parse,吸氣也將出席預期:

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

它是推薦ReflectDecorators(但不是必需的)一起使用。如果您選擇跳過此建議,則還需要爲成員指定「類型」設置,例如:

@JsonMember({ type: String }) 
public id: string;