Is it possible to make class-transformer use getters/setters when converting to/from json

939 views Asked by At

Let's suppose I have a json:

{"firstName": "Mike", "age": 35}

And a class:

export class Person {
     
    private firstName: StringProperty = new SimpleStringProperty();
    
    private age: IntegerProperty = new SimpleIntegerProperty();
    
    public constructor() {
        //does nothing
    }
    
    public setFirstName(firstName: string): void {
        this.firstName.set(firstName);
    }
    
    public getFirstName(): string {
        return this.firstName.get();
    }
    
    public setAge(age: number): void {
        this.age.set(age);
    }
    
    public getAge(): number {
        return this.age.get();
    }
    
}

Can I make class-transformer use getters/setters when converting to/from json?

1

There are 1 answers

0
Eldar On

Well you can do it basically using Object.assign but you need to use actual getters and setter like below :

const json  = {"firstName": "Mike", "age": 35};

 class Person {
     
    private _firstName: string |null = null;
    
    private _age: number |null = null;
    
    public constructor() {
        //does nothing
    }
    
    public set firstName(firstName: string|null) {
         //+some logic
        this._firstName = firstName;
    }
    
    public get firstName(){
        //+some logic
        return this._firstName;
    }
    
    public set age(age: number |null) {
         //+some logic
        this._age = age;
    }
    
    public get age(){
         //+some logic
        return this._age;
    }
    
}

var person = new Person();
Object.assign(person,json);

console.log(person);

console.log(person.firstName,person.age);

Edit: This might be dangerous if source jsons properties differ from the target class. That might add some additional properties to the instance which is not visible to type system. So you may want to use Object.seal method. Playground Link