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

TypeScript中MyInt64类自定义JSON序列化与反序列化问题

解决方案

1. 实现MyInt64类(默认序列化输出字符串)

首先定义MyInt64类,维护原始输入字符串并重写toJSON()方法,确保默认JSON.stringify输出字符串形式的大数,避免截断:

import JSONBig from 'json-bigint';

class MyInt64 {
  private readonly rawValue: string;
  public readonly value: bigint;

  constructor(strValue: string) {
    // 验证输入为合法整数字符串
    if (!/^-?\d+$/.test(strValue)) {
      throw new Error('MyInt64仅接受整数格式的字符串');
    }
    this.rawValue = strValue;
    this.value = BigInt(strValue);
  }

  // 重写toJSON,默认序列化返回原始字符串
  toJSON(): string {
    return this.rawValue;
  }

  // 可选:方便调试的toString方法
  toString(): string {
    return this.rawValue;
  }
}

2. 封装自定义MyJSON工具类(支持精确数字序列化/反序列化)

借助json-bigint库处理大数的精确序列化与反序列化,封装MyJSON工具类实现自定义逻辑:

export const MyJSON = {
  // 自定义序列化:将MyInt64转为精确数字
  stringify<T>(value: T): string {
    const jsonBig = JSONBig({ storeAsString: false });
    return jsonBig.stringify(value, (_, val) => {
      if (val instanceof MyInt64) {
        return val.value; // 传递BigInt给json-bigint处理为精确数字
      }
      return val;
    });
  },

  // 自定义反序列化:将JSON中的数字/字符串转回MyInt64
  parse<T>(jsonStr: string): T {
    const jsonBig = JSONBig({ storeAsString: true });
    const parsed = jsonBig.parse(jsonStr);

    // 递归遍历对象,将BigInt字段转回MyInt64实例
    const convertToMyInt64 = (obj: any): any => {
      if (typeof obj === 'object' && obj !== null) {
        for (const key in obj) {
          if (Object.prototype.hasOwnProperty.call(obj, key)) {
            if (typeof obj[key] === 'bigint') {
              obj[key] = new MyInt64(obj[key].toString());
            } else if (typeof obj[key] === 'object') {
              obj[key] = convertToMyInt64(obj[key]);
            }
          }
        }
      }
      return obj;
    };

    return convertToMyInt64(parsed) as T;
  }
};

3. 测试场景验证

用你提供的IUser示例验证两种序列化逻辑:

interface IUser {
  id: MyInt64;
  name: string;
  balance: number;
}

const user: IUser = {
  id: new MyInt64("9223372036854775807"),
  name: "Alice",
  balance: 123
};

// 常规序列化:输出字符串形式的id
const userString1 = JSON.stringify(user);
console.log(userString1);
// 输出结果:{"id":"9223372036854775807","name":"Alice","balance":123}

// 自定义序列化:输出精确数字形式的id
const userStringCustom = MyJSON.stringify(user);
console.log(userStringCustom);
// 输出结果:{"id":9223372036854775807,"name":"Alice","balance":123}

// 自定义反序列化验证
const parsedUser = MyJSON.parse<IUser>(userStringCustom);
console.log(parsedUser.id instanceof MyInt64); // true
console.log(parsedUser.id.value); // 9223372036854775807n

关键逻辑说明

  • 默认序列化:通过重写MyInt64的toJSON()方法,让JSON.stringify自动将实例转为原始字符串,彻底避免大数截断问题。
  • 自定义精确序列化:利用json-bigint对BigInt的支持,将MyInt64内部的bigint值传递给库处理,生成无截断的数字格式JSON。
  • 反序列化:通过json-bigint解析出精确的BigInt值,再递归转换为MyInt64实例,保证类型一致性。

依赖安装

如果未安装json-bigint,执行以下命令:

npm install json-bigint
# 或 yarn add json-bigint

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:50:43