无需外部库,如何将JSON对象转换为TypeScript类实例?
将JSON转换为TypeScript类实例的通用方案
如果你想把JSON对象转换成TypeScript类的实例(能访问类的方法),同时支持嵌套对象,不用为每个类写单独的工厂方法,可以试试以下几种通用方案:
1. 基础通用转换函数(支持嵌套)
这个方案通过实例化目标类,再递归复制JSON属性,同时支持通过类的静态属性指定嵌套对象对应的类:
// 嵌套类示例 class Address { public street: string = ''; public city: string = ''; getFullAddress(): string { return `${this.street}, ${this.city}`; } } // 主类,通过static nestedTypes指定嵌套类型 class Person { public firstName: string = ''; public lastName: string = ''; public address: Address = new Address(); // 静态属性:定义当前类中嵌套属性对应的类 static nestedTypes: Record<string, new () => any> = { address: Address }; getName(): string { return `${this.firstName} ${this.lastName}`; } } // 通用转换函数 function toInstance<T>(json: Partial<T>, clazz: new () => T & { nestedTypes?: Record<string, new () => any> }): T { const instance = new clazz(); const nestedTypeMap = clazz.nestedTypes || {}; for (const key in json) { if (!json.hasOwnProperty(key)) continue; const value = json[key]; // 处理嵌套对象:如果是对象且有对应的嵌套类,递归转换 if (typeof value === 'object' && value !== null && !Array.isArray(value)) { const nestedClass = nestedTypeMap[key]; instance[key] = nestedClass ? toInstance(value, nestedClass) : value; } else { instance[key] = value; } } return instance; } // 使用示例 const personJson = { firstName: "Max", lastName: "Mustermann", address: { street: "Main St 1", city: "Berlin" } }; const personInstance = toInstance(personJson, Person); console.log(personInstance.getName()); // 输出 "Max Mustermann" console.log(personInstance.address.getFullAddress()); // 输出 "Main St 1, Berlin"
2. 原型替换法(简化版,无构造函数执行)
如果你的类构造函数没有复杂的初始化逻辑(比如不需要设置默认值、处理参数),可以直接修改JSON对象的原型,快速获得类实例:
function toInstance<T>(json: any, clazz: new () => T): T { const instance = Object.create(clazz.prototype); Object.assign(instance, json); return instance; } // 使用示例 const json = { firstName: "Max", lastName: "Mustermann" }; const person = toInstance(json, Person); console.log(person.getName()); // 输出 "Max Mustermann"
注意:这种方式不会调用类的构造函数,所以如果类里有构造函数初始化的属性(比如默认值),JSON中未提供的属性会保持undefined,而不是构造函数里的默认值。
3. 带外部类型映射的版本
如果不想在类内部添加静态属性,可以传入一个外部类型映射表来指定嵌套关系:
// 定义类型映射 const typeMap: Record<string, new () => any> = { address: Address }; function toInstance<T>(json: Partial<T>, clazz: new () => T, nestedMap?: Record<string, new () => any>): T { const instance = new clazz(); const map = nestedMap || {}; for (const key in json) { if (!json.hasOwnProperty(key)) continue; const value = json[key]; if (typeof value === 'object' && value !== null && !Array.isArray(value)) { const nestedClass = map[key]; instance[key] = nestedClass ? toInstance(value, nestedClass, map) : value; } else { instance[key] = value; } } return instance; } // 使用示例 const personInstance = toInstance(personJson, Person, typeMap);
以上方案可以根据你的类结构和需求选择,既不用为每个类写单独的工厂方法,也能支持嵌套对象的转换。
内容的提问来源于stack exchange,提问作者Zharin
相关产品推荐
相关产品推荐

