Angular中使用typescript-json-serializer映射JSON的function字段问题
解决Angular中映射JSON的'function'字段问题
你遇到的问题是因为typescript-json-serializer对构造函数参数的装饰器处理存在限制,或是反序列化调用方式不正确,下面是几个可行的解决办法:
方案1:将字段定义为类属性而非构造函数参数
把@JsonProperty装饰器放在类的属性上,而非构造函数参数,让库的映射逻辑更容易识别:
import {JsonObject, JsonProperty} from "typescript-json-serializer"; @JsonObject() export class Process{ public id: number; public createdBy: string; @JsonProperty("function") public _function: string; constructor(id: number, createdBy: string, _function: string) { this.id = id; this.createdBy = createdBy; this._function = _function; } }
方案2:确保正确使用库的反序列化方法
必须使用typescript-json-serializer提供的deserialize方法转换JSON,不能直接用new Process()或JSON.parse():
import {deserialize} from "typescript-json-serializer"; // 假设后端返回的响应数据是responseData const processInstance = deserialize(responseData, Process);
方案3:手动映射(无需依赖库)
如果库的问题难以排查,直接写静态方法手动转换JSON,更可控:
export class Process{ public id: number; public createdBy: string; public _function: string; private constructor(id: number, createdBy: string, _function: string) { this.id = id; this.createdBy = createdBy; this._function = _function; } static fromJson(json: any): Process { return new Process( json.id, json.createdBy, json.function // 直接读取JSON的'function'键 ); } } // 使用示例 const processInstance = Process.fromJson(responseData);
额外检查项
确保你的tsconfig.json中启用了装饰器相关配置:
{ "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true } }
内容的提问来源于stack exchange,提问作者tshiamotman
相关产品推荐
相关产品推荐

