可以使用JSON+第三方库class-transformer实现,参考代码如下://ohpm install class-transformer安装库 import { Expose } from 'class-transformer'; //定义一个class接收数据 export class User { constructor() { this.id= 0 this.firstName= "" this.lastName= "" } @Expose({ name: 'uid' }) id: number; firstName: string; lastName: string; @Expose({ name: 'fullName' }) getFullName() { return this.firstName + ' ' + this.lastName; } } //测试方法 jsonTest() { let json:string = "{\"uid\": 10,\"firstName\": \"CCC\",\"lastName\": \"Khudoiberdiev\"}" let fromPlainUser:User = JSON.parse(json) let user:User = plainToInstance(User,fromPlainUser) console.info(JSON.stringify(user)) // 输出{"id":10,"firstName":"CCC","lastName":"Khudoiberdiev"} console.info(JSON.stringify(instanceToPlain(user,{}))) //输出{"uid":10,"firstName":"CCC","lastName":"Khudoiberdiev","fullName":"CCC Khudoiberdiev"} }
可以使用JSON+第三方库class-transformer实现,参考代码如下: