首页 > 解决方案 > 转换到/从 json 时,是否可以让类转换器使用 getter/setter

问题描述

假设我有一个json:

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

还有一个类:

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

我可以在转换到/从 json 时让类转换器使用 getter/setter 吗?

标签: typescriptclass-transformer

解决方案


好吧,您基本上可以使用Object.assign,但您需要使用实际的 getter 和 setter,如下所示:

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

编辑:如果源 jsons 属性与目标类不同,这可能很危险。这可能会向实例添加一些对类型系统不可见的附加属性。所以你可能想使用Object.seal方法。 游乐场链接


推荐阅读