【问题标题】:Deserialize JSON Object with arrays in Typescript在 Typescript 中使用数组反序列化 JSON 对象
【发布时间】:2019-04-18 17:08:46
【问题描述】:

我想反序列化 Typescript 中的 JSON 对象。我找到了这个相关的question 我想使用已接受答案的approach 4。但是我不确定这是否适用于我的情况,因为该对象具有其他对象的arrays 的成员,array 中的对象也是如此。此外,我想使用一种通用方法/方法来反序列化对象,即使不知道对象依赖关系在哪里结束。对象结构如下:

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>;
...

}

...

如何反序列化这些类型的对象?即使有一种将对象结构的结束视为理所当然的方法,我也会感到满意。

【问题讨论】:

  • 那个链接失效了
  • 你能添加一个你想要反序列化的json的例子吗?

标签: json typescript deserialization


【解决方案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;
    }

}

【讨论】:

    【解决方案2】:

    为了避免列出所有属性,我使用了link

    前提是要有一个类实现的可反序列化接口:

    export interface Deserializable {
       deserialize(input: any): this;
    }
    

    然后我们使用 Object.assign。

    类:

    class Parent {
        s: string;
        x: number;
        children: Child1[] = [];
    
        deserialize(input) {
            Object.assign(this, input);
            let deserializedChildren: Child1[] = [];
            for(let child of input.children){
                deserializedChildren.push(new Child1().deserialize(child))
            }
            this.children = deserializedChildren;
            return this;
        }
    }
    
    class Child1{
        t: string;
        y: number;
    
        deserialize(input) {
            Object.assign(this, input);
            return this;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-14
      • 2017-07-31
      • 2016-05-23
      • 1970-01-01
      • 2015-06-11
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多