You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JS中实现含Map的类与JSON字符串的互转?

解决TypeScript类实例含Map的JSON互转问题

问题核心

你碰到的c.toMyString is not a function错误,本质是**JSON.parse返回的是普通JavaScript对象,不是类A的实例**——TypeScript的as A只是类型断言,不会给对象添加类的方法和原型链。

可行方案:自动处理序列化与反序列化

不用手动拼接JSON或逐个列属性,利用JSON.stringify的自动调用逻辑和类的静态方法,实现Map与大量属性的自动互转:

class A {
    map1: Map<number, number> = new Map();
    map2: Map<string, string> = new Map();
    age: number = 0;
    // 其他大量属性...

    // JSON.stringify会自动调用此方法,完成Map转数组
    toJSON() {
        const plainObj = { ...this };
        // 遍历属性,把所有Map转为JSON支持的数组格式
        for (const key in plainObj) {
            if (plainObj[key] instanceof Map) {
                plainObj[key] = Array.from(plainObj[key].entries());
            }
        }
        return plainObj;
    }

    // 静态方法:从JSON字符串恢复类实例
    static fromJSON(jsonStr: string): A {
        const plainObj = JSON.parse(jsonStr);
        const instance = new A();
        // 遍历属性,把数组转回Map,其他属性直接赋值
        for (const key in plainObj) {
            if (Array.isArray(plainObj[key])) {
                instance[key] = new Map(plainObj[key]);
            } else {
                instance[key] = plainObj[key];
            }
        }
        return instance;
    }

    toMyString() {
        return JSON.stringify(this); // 直接复用toJSON逻辑,不用手动拼接
    }
}

// 测试流程
const a = new A();
a.map1.set(1, 1);
a.map1.set(2, 2);
a.map2.set('1', '1');
a.map2.set('2', '2');
a.age = 25;

// 序列化到JSON字符串
const jsonStr = a.toMyString();
console.log('序列化结果:', jsonStr);

// 从JSON恢复实例
const restoredA = A.fromJSON(jsonStr);
console.log('恢复后的map1值:', restoredA.map1.get(1)); // 输出1
console.log('调用类方法结果:', restoredA.toMyString()); // 正常执行

方案优势

  • 自动处理所有属性,不用手动列举大量字段
  • 序列化/反序列化逻辑统一,后续新增属性无需修改代码
  • 严格保证恢复后的对象是类A的实例,拥有所有类方法

内容的提问来源于stack exchange,提问作者little

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:57:47