2016-02-19 29 views
7

複雑なjsonオブジェクトをTypeSciptでどのように解析できますか?複雑なjsonオブジェクトをTypeScriptで解析する

私には顧客オブジェクトがあり、請求書があります。

これは私のモデルである:

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

そして、私のサービスで私が持っている:

顧客データが(私の顧客ID、名前などは、いくつかの値を持っている)素晴らしいですが、請求書がnullである

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

jsonは正しいです、data.Invoices.lengthは数値を返します。

+1

詳細が不十分です。 – dfsq

答えて

8

複雑なjsonオブジェクトをTypeSciptでどのように解析できますか?

あなたが実際のクラスのインスタンスの代わりに、簡単なJavaScriptオブジェクトにJSONを解析する意味と仮定すると、活字体は、この機能を出荷しない既製

あなたはややJSONが信頼されて場合は型の安全性を模倣するために、あなたがtype-assertion(ないタイプ - をキャスト)行うことができます使用して、インターフェイスの宣言を作成するかもしれないが、それはそれだ - 私はネイティブなツールを知っていません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文字列をデシリアライズするには、あなたの代わりにJSON.parseのTypedJSON.parse使用する予想通り、ゲッターも存在します。

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

ReflectDecorators(必須ではありません)で使用するをお勧めします。この推奨事項をスキップする場合は、メンバーの 'タイプ'設定も指定する必要があります。

@JsonMember({ type: String }) 
public id: string; 
関連する問題