JSON deserialization for Typescript class

Viewed 21

Assume I have this class in TypeScript that accepts a number and customizes the JSON serialization by converting it into human readable date and labelling it as dob.

    class Foo {
        private readonly seconds: number
        constructor(seconds: number) {
            this.seconds = seconds;
        }
        toJSON(){
            return {dob: new Date(this.seconds * 1000).toDateString()};
        }
    }

Now I construct an object of Foo and serialize it to JSON

    const foo = new Foo(1663962526);
    console.log(JSON.stringify(foo));

and I get this as output

{\"dob\":\"Fri Sep 23 2022\"}

now I take this String back and try to form the instance of Foo again.

    const reconstructedFoo = JSON.parse("{\"dob\":\"Fri Sep 23 2022\"}")
    console.log(reconstructedFoo.seconds) // this is undefined
    console.log(isNaN(reconstructedFoo.seconds))

Ofcourse, it doesn't fit into shape of Foo - how do override the deserialization of JSON into instance (like i did by toJSON for serialization)

0 Answers
Related