2016-11-06 54 views
1

我想反序列化一個JSON對象Typescript。我發現這個有關question我想用接受答案的approach 4。不過,我不確定這是否適用於我的情況,因爲該對象具有其他對象的成員arrays,因此對象也在array中。此外,我想使用一種泛型方法/方法,即使不知道對象依賴關係的結束位置,也可以對對象進行反序列化。對象結構如下所示:在字典中反序列化帶有數組的JSON對象

class Parent { 

s: string; 
x: number; 
children : Array<Child1> 
... 

} 

class Child1 { 

t: string; 
y: number; 
children : Array<Child2> 
... 

} 

class Child2 { 

k: string; 
z: number; 
children : Array<Child3>; 
... 

} 

... 

如何反序列化這些類型的對象?即使將對象結構的末端視爲理所當然,我也會滿意的。

+0

這鏈接不起作用 – martin

+0

你可以添加你要反序列化JSON的例子嗎? –

回答

1

我不確定我是否理解您的全部要求,但您說要使用的方法基本上使每個類都負責反序列化自身。所以如果父母知道它有一個Child1數組,它知道它可以遍歷json中的children數組,然後調用Child1來反序列化每個孩子。然後Child1可以做同樣爲它的孩子,等等:

class Parent { 
    s: string; 
    x:number; 
    children: Child1[] = []; 

    deserialize(input) { 
     this.s = input.s; 
     this.x = input.x; 
     for(let child of input.children){ 
      this.children.push(new Child1().deserialize(child)) 
     } 
     return this; 
    } 
} 

class Child1{ 
    t: string; 
    y: number; 
    children: Child2[] = [] 
    deserialize(input) { 
     this.t = input.t; 
     this.y = input.x; 
     for(let child of input.children){ 
      this.children.push(new Child2().deserialize(child)) 
     } 

     return this; 
    } 
} 

class Child2{ 
    deserialize(input) { 
     //... 
     return this; 
    } 

}