I have the following Typescript code:
class Foo {
private _id: number;
private _desc: string;
constructor(id: number, desc: string) {
this._id = id;
this._desc = desc;
}
public get id(): number {
return this.id;
}
public set id(value: number) {
this._id = value;
}
public get desc():string {
return this.desc;
}
public set desc(value: string) {
this._desc = value;
}
}
let foo = new Foo(1, 'something');
I would like to get a string from a Typescript class, I mean with getter and setter. Then I should get the following string:
{"id":1,"desc":"something"}
According to this answer I can reach that adding the following method to the class:
public toJSONString(): string {
return JSON.stringify(this, Object.keys(this.constructor.prototype));
}
It works.
It doesn't work if the Typescript class contains any other sub class.
So if I have the following code:
class Foo {
private _id: number;
private _desc: string;
private _user: Bar;
constructor(id: number, desc: string, user: Bar) {
this._id = id;
this._desc = desc;
this._user = user;
}
public get id(): number {
return this._id;
}
public set id(value: number) {
this._id = value;
}
public get desc():string {
return this._desc;
}
public set desc(value: string) {
this._desc = value;
}
public get user(): Bar {
return this._user;
}
public set user(value: Bar) {
this._user = value;
}
public toJSONString(): string {
return JSON.stringify(this, Object.keys(this.constructor.prototype));
}
}
class Bar {
private _name: string;
private _surname: string;
constructor(name: string, surname: string) {
this._name = name;
this._surname = surname;
}
public get name(): string {
return this._name;
}
public set name(value: string) {
this._name = value;
}
public get surname():string {
return this._surname;
}
public set surname(value: string) {
this._surname = value;
}
}
let foo = new Foo(1, 'something', new Bar('foo', 'bar'));
If I use toJSONString
method I get the following string:
{"id":1,"desc":"something","user":{}}
instead of this:
{"id":1,"desc":"something","user":{ "name": "foo", "surname": "bar"}}
So, how can I get a string from a Typescript class that has other sub classes?
(If you need here is the playground for the first code and here is the playground for the second code)