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

JavaScript中如何将类转换为JSON对象?

解决方案

1. 无构造函数的类定义

先把类改成直接声明类字段,无需通过constructor初始化:

class ClassExample {
  // 直接定义类属性,不用构造函数赋值
  name = '';
  mapOfClassExample = new Map();
}

2. 保留类型信息的序列化函数

JSON本身不支持自定义类型,我们可以给需要保留类型的结构添加类型标记,让序列化后的JSON携带类型信息:

function intoJSON(instance) {
  return JSON.stringify(instance, (key, value) => {
    // 给ClassExample实例添加类型标识
    if (value instanceof ClassExample) {
      return {
        __type: 'ClassExample',
        name: value.name,
        mapOfClassExample: value.mapOfClassExample
      };
    }
    // 给Map添加类型标识
    if (value instanceof Map) {
      return {
        __type: 'Map',
        value: Object.fromEntries(value)
      };
    }
    return value;
  });
}

3. 可选:反序列化恢复原类型

如果需要把JSON还原回原类实例和Map结构,可以补充一个解析函数:

function parseJSON(jsonStr) {
  return JSON.parse(jsonStr, (key, value) => {
    // 恢复ClassExample实例
    if (value?.__type === 'ClassExample') {
      const instance = new ClassExample();
      instance.name = value.name;
      instance.mapOfClassExample = parseJSON(JSON.stringify(value.mapOfClassExample));
      return instance;
    }
    // 恢复Map结构
    if (value?.__type === 'Map') {
      return new Map(Object.entries(value.value));
    }
    return value;
  });
}

示例使用

// 创建实例(无需构造函数传参)
const example = new ClassExample();
example.name = 'test';
example.mapOfClassExample.set('key', 'value');

// 序列化
const json = intoJSON(example);
// 输出JSON包含类型标记:{"__type":"ClassExample","name":"test","mapOfClassExample":{"__type":"Map","value":{"key":"value"}}}

// 反序列化(可选)
const restoredInstance = parseJSON(json);
console.log(restoredInstance instanceof ClassExample); // true
console.log(restoredInstance.mapOfClassExample instanceof Map); // true

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:42:28