导航菜单

json2http
JSON 转 HTTP 请求代码
一键生成多语言接口代码

一份 JSON5 接口配置,自动生成 多种语言 的 HTTP 请求代码和实体类。 内置 多种 Agent,专为 微信小程序 TypeScript 环境优化 typescript_weixin@3

JSON转HTTP代码 微信小程序TS 多Agent 接口代码生成 多语言
快速安装
npx json2http build -l typescript@5 -a typescript_weixin@3

核心能力:JSON 转实体类 & HTTP 请求代码

json2http 从 JSON5 接口配置到类型安全的 HTTP 请求代码,覆盖请求生成、Agent 适配、序列化、容错处理全链路

JSON → HTTP 请求代码

一份 JSON5 接口配置,自动生成完整的 HTTP 请求代码(Plan + Agent + 参数/响应类),内置多种 Agent 适配各平台网络库。

dio@5 rcp@12 axios@1 fetch@0 weixin@3 okhttp@4 alamofire@5

序列化 / 反序列化

生成的实体类自带 fromJson()toJson()fromPreset()toNew() 四种方法,请求参数和响应数据自动序列化。

类型引用 & 递归支持

通过 $meta.ref 引用跨文件类型,支持递归结构(如树形、链表),避免重复定义。

可选字段 & 默认值

字段名加 ? 后缀即可声明可选(nullable),未标记字段自动赋予类型默认值,告别繁琐的 null 检查。

数据容错规则

四种规则控制异常数据处理:DiffType(类型不匹配)、MissKey(缺失字段)、MoreIndex/MissIndex(数组越界),全局/实例/单次三级配置。

JSON → 多语言实体类 (底层依赖)

json2class 是 json2http 的底层依赖,自动生成 Dart、ArkTS、TypeScript、Kotlin、Swift 等多种语言的类型安全实体类代码,也可独立使用。

Dart@3 ArkTS@12 TS@5 Kotlin@1.3 Swift@5.7

微信小程序 TS Agent — 小程序 Agent 最佳实践

typescript_weixin@3 — 专为微信小程序打造的 HTTP Agent

json2http 是目前唯一内置微信小程序 TypeScript Agent 的 JSON 代码生成工具,直接封装 wx.request(),无需 polyfill,支持分包懒加载、Token 刷新、全局拦截。

wx.request()
原生封装,零 polyfill
require.async()
分包懒加载架构
setPlan
全局拦截 & Token 刷新
FormData
自定义 UTF-8 编码

1 编写 JSON5 接口配置

api.json5
{
  '/api/blood/index': {
    title: '宝宝血型计算',
    method: 'GET',
    params: {
      father: '',
      mother: '',
    },
    res: {
      code: 0,
      msg: '',
      data: {
        possible: [''],
        impossible: [''],
      },
    },
  },
}

2 运行生成命令(指定微信小程序 Agent)

terminal
npx json2http build -l typescript@5 -a typescript_weixin@3

3 生成的 TypeScript 代码(自动包含 WeixinAgent)

json2http.ts(生成产物)
// 自动生成的请求 Plan 类
export class apibloodindexplan extends Plan {
  path = '/api/blood/index';
  readonly title = '宝宝血型计算';
  method = 'GET';
  res = new apibloodindexres();
  params = new apibloodindexparams();
  body = null;
  headers = {};
}

// 自动生成的响应实体类
export class apibloodindexres extends Json2class {
  code: number = 0;
  msg: string = '';
  data: apibloodindexresdata = new apibloodindexresdata();
}

export class apibloodindexresdata extends Json2class {
  possible: string[] = [];
  impossible: string[] = [];
}

// 自动生成的参数实体类
export class apibloodindexparams extends Json2class {
  father: string = '';
  mother: string = '';
}

4 在微信小程序中使用

project.d.ts — 类型声明
type JSON2HTTP = typeof import('./miniprogram/json2http/json2http');

interface IAppOption {
  json2http: Promise<JSON2HTTP>;
}
app.ts — 全局配置 & 分包加载
App<IAppOption>({
  json2http: require.async('./json2http/json2http').then((e) => {
    // 全局配置:baseURL、错误处理、Token 刷新
    e.Json2http.setPlan = (plan) => {
      plan.baseURL = 'https://api.example.com';
      plan.process = (reply) => {
        if (reply.data?.code !== 200) {
          reply.error = reply.data?.msg;
        }
      };
    };
    return e;
  }),
});
page.ts — 页面中使用
Page({
  onLoad: async function() {
    const app = getApp<IAppOption>();
    const json2http = await app.json2http;

    // 类型安全的请求调用
    const result = await json2http.Json2http.single.apibloodindex((p) => {
      p.params.father = 'A';
      p.params.mother = 'O';
    });

    // 类型安全的响应访问
    console.log(result.res.data.possible);   // string[]
    console.log(result.res.data.impossible); // string[]
    console.log(result.res.code);            // number
    console.log(result.res.msg);             // string
  }
});

为什么选择 WeixinAgent 而不是 Axios 或 Fetch?

特性 typescript_weixin@3 typescript_axios@1 typescript_fetch@0
微信小程序原生支持✅ wx.request()❌ 需 polyfill❌ 需 polyfill
分包懒加载✅ require.async()
Multipart FormData✅ 自定义编码⚠️ 部分
ArrayBuffer 支持
Token 自动刷新✅ plan.after⚠️ 手动
包体积影响✅ 零依赖❌ +13KB⚠️ 需 polyfill

快速使用教程:TS 实体生成 & 接口代码

三步上手 json2http,一份配置生成完整的 HTTP 请求代码

H json2http — HTTP 请求代码生成

1安装 & 运行

# 默认使用 fetch Agent
npx json2http build -l typescript@5

# 指定微信小程序 Agent
npx json2http build -l typescript@5 -a typescript_weixin@3

2编写接口配置

// api.json5
{
  '/api/user/info': {
    title: '获取用户信息',
    method: 'GET',
    params: { id: '' },
    res: {
      code: 0,
      data: { name: '', avatar: '' },
    },
  },
}

3使用生成的代码

// 全局配置
Json2http.setPlan = (p) => {
  p.baseURL = 'https://api.example.com';
};

// 发起请求
const result = await Json2http.single.apiuserinfo((p) => {
  p.params.id = '123';
});
console.log(result.res.data.name);    // string
console.log(result.res.data.avatar);  // string

C json2class — 实体类生成 (底层依赖,也可独立使用)

1安装

npx json2class build -l typescript@5

2配置

// user.json5
{ 
    "user": { 
        "id": 0, 
        "name": "", 
        "email?": "" 
    } 
}

3使用

const user = new rootuser();
user.fromJson({ id: 1, name: 'Tom' });
console.log(user.name); // "Tom"

微信小程序专项 — 四步上手

Step 1

生成代码

指定 -a typescript_weixin@3 生成微信小程序专用代码

Step 2

配置类型声明

project.d.ts 中声明 IAppOption 接口

Step 3

配置分包加载

app.json 中添加 subPackages,在 app.ts 中用 require.async() 懒加载

Step 4

页面中调用

通过 getApp().json2http 获取实例,类型安全地调用接口

CLI 参数一览

参数 说明 示例
-l, --language目标语言(必填)typescript@5, dart@3
-a, --default-agentHTTP Agent(json2http 专用)typescript_weixin@3
-s, --searchJSON 配置搜索目录./config
-o, --output输出目录./src/generated
-p, --package包名com.example.app
-d, --debug启用调试输出

代码生成演示:JSON 转实体类 & HTTP 请求

一份 JSON5 接口配置 → Plan + Agent + 参数/响应实体类,一键生成完整的 HTTP 请求代码

输入:JSON5 接口配置

api.json5
{
  '/api/order/detail': {
    title: '订单详情',
    method: 'GET',
    params: { id: '' },
    res: {
      code: 0,
      data: {
        id: 0,
        status: '',
        items?: [""],       // 可选数组
        total: 0,
        address: {
          city: '',
          street: '',
          zip: '',
        },
      },
    },
  },
}

输出:HTTP 请求代码(Plan + Agent + 实体类)

json2http.ts (Plan + Agent + 实体类)
// ===== Plan 配置 =====
export const Plan = {
  '/api/order/detail': { method: 'GET', title: '订单详情' },
};

// ===== Agent 请求方法 =====
export class Json2http {
  static setPlan: (p: any) => void;

  static single = {
    apiorderdetail: async (fn: (p: any) => void) => {
      const p = new apiorderdetailparams();
      fn(p);
      // fetch 请求逻辑...
      return { res: new apiorderdetailres().fromJson(response) };
    },
  };
}

// ===== 参数实体类 =====
export class apiorderdetailparams extends Json2class {
  id: string = '';
}

// ===== 响应实体类 =====
export class apiorderdetailres extends Json2class {
  code: number = 0;
  data: apiorderdetailresdata = new apiorderdetailresdata();
}

export class apiorderdetailresdata extends Json2class {
  id: number = 0;
  status: string = '';
  items: string[] | null = null;  // 可选字段
  total: number = 0;
  address: apiorderdetailresdataaddress = new apiorderdetailresdataaddress();

  fromJson(data: any, rule?: Rule): apiorderdetailresdata { /* ... */ }
  toJson(): object { /* ... */ }
}

export class apiorderdetailresdataaddress extends Json2class {
  city: string = '';
  street: string = '';
  zip: string = '';
}

高级特性

类型引用、递归结构、自定义 Agent、Token 刷新

类型引用 & 递归结构

tree.json5 — 递归引用
{
  "treeNode": {
    "value": 0,
    "left": { "$meta": { "ref": "/tree#/treeNode" } },
    "right": { "$meta": { "ref": "/tree#/treeNode" } },
  },
}

使用 $meta.ref 引用自身实现递归类型(树、链表),也可跨文件引用 /filename#/path

自定义 Agent & Token 刷新

自定义 Agent 示例
// 替换特定接口的 Agent
class XAgent extends Agent {
  async fetch(plan: Plan): Promise<Reply> {
    plan.reply.data = { statusCode: '0' };
    return plan.reply;
  }
}

Json2http.setPlan = (plan) => {
  plan.agent = new XAgent();  // 全局替换
};

// Token 自动刷新
plan.after = async () => {
  if (plan.reply.error === 'token expired') {
    const refreshed = await Json2http.single.refreshtoken((p) => {
      p.headers['token'] = plan.headers['token'];
    });
    plan.headers['token'] = refreshed.res.data;
    await plan.fetch();  // 自动重试
  }
};

Agent 可全局替换或单次替换,支持 plan.after 钩子实现 Token 刷新自动重试。

数据容错规则

规则场景可选值
DiffType类型不匹配Keep / Default / Null
MissKey字段缺失Keep / Default / Null
MoreIndex数组多余元素Fill / Drop / Null
MissIndex数组缺失元素Fill / drop / Null / Skip

三级配置:全局默认 → 实例级 → 单次调用级,灵活控制数据容错策略。

HTTP Body 类型支持

jsonJSON 序列化请求体
mapURL-encoded 表单数据
formMultipart 表单(支持文件上传)
plain纯文本请求体
byte二进制数据请求体

微信小程序 Agent 对 form 类型提供自定义 UTF-8 编码和 boundary 生成。

常见问题 — json2http JSON 转实体类 & 小程序 Agent

json2http 和 json2class 有什么区别?

json2http 是主要工具,从 JSON5 接口配置生成完整的 HTTP 请求代码(Plan、Agent、参数/响应实体类),内置多种 Agent 适配各平台网络库。

json2class 是 json2http 的底层依赖,负责生成实体类代码(fromJson/toJson 等序列化方法),也可独立使用于纯数据模型定义场景。

需要接口请求时直接用 json2http,它会自动包含实体类生成能力。

微信小程序为什么要用 typescript_weixin@3 Agent?

微信小程序运行在沙箱环境中,不支持 XMLHttpRequest 和 fetch API。Axios 等库需要 polyfill 才能运行,增加包体积和兼容性风险。

typescript_weixin@3 直接封装 wx.request(),零依赖零 polyfill,还支持 require.async() 分包懒加载,是微信小程序的最佳选择。

JSON5 和 JSON 有什么区别?

JSON5 是 JSON 的扩展,支持注释、尾逗号、无引号键名、多行字符串等,更适合人类编写和阅读配置文件。json2http 同时支持 JSON 和 JSON5 格式输入。

可选字段怎么定义?

在字段名后加 ? 即可声明为可选(nullable)。例如 "email?": "" 生成 email: string | null = null

数组元素也可标记可选:"items?": ["", null] 表示数组本身可为 null,元素也可为 null。

生成的代码可以修改吗?

生成的代码不建议手动修改,因为下次生成会覆盖。推荐通过 JSON 配置调整,或利用 Agent 继承机制扩展功能。json2http 的 Agent 是可替换的,你可以继承 Agent 抽象类实现自定义逻辑。

支持哪些安装方式?
  • 推荐:Node.js 环境 npx json2class build -l typescript@5
  • Flutter/Dart:dart pub add dev:json2class + dart run json2class build -l dart@3
  • HarmonyOS:ohpm install json2class --save-dev + ohpm run json2class
未来还会支持哪些语言?

计划支持 Java 和 Objective-C。当前已支持 Dart@3、ArkTS@12、TypeScript@5、Kotlin@1.3、Swift@5.7 等多种语言。

开源 & 免费

json2http 采用 ISC 协议开源,完全免费使用