typescript - 转换到/从 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 吗?
解决方案
好吧,您基本上可以使用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
方法。
游乐场链接
推荐阅读
- ansible - Ansible 库存:使用主机变量定义组从属关系
- sql - 使用嵌套行(类型 STRUCT)对表 SQL 进行重复数据删除
- android - 错误:无法找到带有 Gradle 路径“:capacitor-cordova-android-plugins”的模块
- java - 如何从数组中的列表视图中获取值
- lmdb - 在特定情况下,LMDB 是否也可以并发写入?
- python - Python 3 Discord Bot 函数添加到自身
- angular - auth0 授权 api 调用返回 200 状态但仍然得到错误响应
- javascript - 如果条件总是运行(钩子,反应状态)
- html - 无法选择形式的单选选项
- python - pybind module.obj:错误 LNK2001:未解析的外部符号