Typescript: Specified Object With Fromjson Method, How To Test If Private Property Exists And Than Set It
i have a object that contains a fromJson method. this method is not working because private property of the class can not be accessed? what is wrong and how to handle it? Code is w
Solution 1:
class Example {
private Foo: string = undefined;
private Foo2: number = undefined;
constructor(input?: string) {
if (!!input) {
this.foo = input;
}
}
set foo(value: string) {
this.Foo = value;
}
get foo(): string {
return this.Foo;
}
set numeric(value: number) {
this.Foo2 = value;
}
get numeric(): number {
return this.Foo2;
}
public static fromJson(obj: Object) {
let result: Example = new Example();
for (let index in obj) {
if (result.hasOwnProperty(index)) {
result[index] = obj[index]; // care, has to be result
}
}
return result;
}
public toJsonString() {
return JSON.stringify(this);
}
public toJsonObject() {
return JSON.parse(this.toJsonString());
}
}
let a = new Example('one');
let json = a.toJsonObject();
let obj = Example.fromJson(json);
console.log(json);
console.log(obj);
i think this is the solution you are looking for. positive effect, if you initialize your properties with undefined, your toJson methods don't list the arguments. so your request traffic is not so big.
Post a Comment for "Typescript: Specified Object With Fromjson Method, How To Test If Private Property Exists And Than Set It"