【问题标题】:Is it possible to make class-transformer use getters/setters when converting to/from json转换到/从 json 时,是否可以让类转换器使用 getter/setter
【发布时间】:2020-10-20 16:40:38
【问题描述】:

假设我有一个 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 时,我可以让 class-transformer 使用 getter/setter 吗?

【问题讨论】:

    标签: typescript class-transformer


    【解决方案1】:

    你基本上可以使用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 方法。 Playground Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-17
      • 2018-06-30
      • 2019-06-25
      • 2015-08-24
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      相关资源
      最近更新 更多