1

I want to deserialize a JSON Object in Typescript. I have found this relevant question I would like to use the approach 4 of the accepted answer. However I am not sure if this would work in my case, since the object has member of arrays of other objects and so do the objects in the array as well. Moreover I would like to use a generic method/approach which deserializes the objects even if one does not know where the object dependencies end. The object structure looks like:

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

}

...

How can I deserialize these type of objects? I would be satisfied even with an approach which takes the end of the object structure for granted.

Community
  • 1
  • 1
arjacsoh
  • 8,932
  • 28
  • 106
  • 166

2 Answers2

2

I'm not sure if I understand your full requirements, but the method that you say you want to use basically makes each class responsible for deserializing itself. So if parent knows it has a Child1 array, it knows it can iterate over the children array in the json and then call on Child1 to deserialize each child. Child1 can then do the same for its children, and so on:

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

}
Daniel Tabuenca
  • 13,147
  • 3
  • 35
  • 38
0

To avoid having to list out all the properties, I used this link.

The premise is to have a deserializable interface which the classes implement:

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

We then make use of Object.assign.

Classes:

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;
    }
}
Fletch
  • 769
  • 1
  • 12
  • 33