JSON → HTTP 请求代码
一份 JSON5 接口配置,自动生成完整的 HTTP 请求代码(Plan + Agent + 参数/响应类),内置多种 Agent 适配各平台网络库。
typescript_weixin@3。
npx json2http build -l typescript@5 -a typescript_weixin@3
{
'/api/user/info': {
method: 'GET',
params: { id: '' },
res: { code: 0, data: { name: '' } }
}
}
// Plan + Agent + 实体类,一键生成
const result = await Json2http.single.apiuserinfo((p) => {
p.params.id = '123';
});
console.log(result.res.data.name); // string
npx json2http build -l typescript@5 -a typescript_weixin@3
json2http 从 JSON5 接口配置到类型安全的 HTTP 请求代码,覆盖请求生成、Agent 适配、序列化、容错处理全链路
一份 JSON5 接口配置,自动生成完整的 HTTP 请求代码(Plan + Agent + 参数/响应类),内置多种 Agent 适配各平台网络库。
生成的实体类自带 fromJson()、toJson()、fromPreset()、toNew() 四种方法,请求参数和响应数据自动序列化。
通过 $meta.ref 引用跨文件类型,支持递归结构(如树形、链表),避免重复定义。
字段名加 ? 后缀即可声明可选(nullable),未标记字段自动赋予类型默认值,告别繁琐的 null 检查。
四种规则控制异常数据处理:DiffType(类型不匹配)、MissKey(缺失字段)、MoreIndex/MissIndex(数组越界),全局/实例/单次三级配置。
json2class 是 json2http 的底层依赖,自动生成 Dart、ArkTS、TypeScript、Kotlin、Swift 等多种语言的类型安全实体类代码,也可独立使用。
typescript_weixin@3 — 专为微信小程序打造的 HTTP Agent
json2http 是目前唯一内置微信小程序 TypeScript Agent 的 JSON 代码生成工具,直接封装 wx.request(),无需 polyfill,支持分包懒加载、Token 刷新、全局拦截。
{
'/api/blood/index': {
title: '宝宝血型计算',
method: 'GET',
params: {
father: '',
mother: '',
},
res: {
code: 0,
msg: '',
data: {
possible: [''],
impossible: [''],
},
},
},
}
npx json2http build -l typescript@5 -a typescript_weixin@3
// 自动生成的请求 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 = '';
}
type JSON2HTTP = typeof import('./miniprogram/json2http/json2http');
interface IAppOption {
json2http: Promise<JSON2HTTP>;
}
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({
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
}
});
| 特性 | typescript_weixin@3 | typescript_axios@1 | typescript_fetch@0 |
|---|---|---|---|
| 微信小程序原生支持 | ✅ wx.request() | ❌ 需 polyfill | ❌ 需 polyfill |
| 分包懒加载 | ✅ require.async() | — | — |
| Multipart FormData | ✅ 自定义编码 | ✅ | ⚠️ 部分 |
| ArrayBuffer 支持 | ✅ | ✅ | ✅ |
| Token 自动刷新 | ✅ plan.after | ✅ | ⚠️ 手动 |
| 包体积影响 | ✅ 零依赖 | ❌ +13KB | ⚠️ 需 polyfill |
三步上手 json2http,一份配置生成完整的 HTTP 请求代码
# 默认使用 fetch Agent
npx json2http build -l typescript@5
# 指定微信小程序 Agent
npx json2http build -l typescript@5 -a typescript_weixin@3
// api.json5
{
'/api/user/info': {
title: '获取用户信息',
method: 'GET',
params: { id: '' },
res: {
code: 0,
data: { name: '', avatar: '' },
},
},
}
// 全局配置
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
npx json2class build -l typescript@5
// user.json5
{
"user": {
"id": 0,
"name": "",
"email?": ""
}
}
const user = new rootuser();
user.fromJson({ id: 1, name: 'Tom' });
console.log(user.name); // "Tom"
指定 -a typescript_weixin@3 生成微信小程序专用代码
在 project.d.ts 中声明 IAppOption 接口
在 app.json 中添加 subPackages,在 app.ts 中用 require.async() 懒加载
通过 getApp().json2http 获取实例,类型安全地调用接口
| 参数 | 说明 | 示例 |
|---|---|---|
| -l, --language | 目标语言(必填) | typescript@5, dart@3 |
| -a, --default-agent | HTTP Agent(json2http 专用) | typescript_weixin@3 |
| -s, --search | JSON 配置搜索目录 | ./config |
| -o, --output | 输出目录 | ./src/generated |
| -p, --package | 包名 | com.example.app |
| -d, --debug | 启用调试输出 | — |
一份 JSON5 接口配置 → Plan + Agent + 参数/响应实体类,一键生成完整的 HTTP 请求代码
{
'/api/order/detail': {
title: '订单详情',
method: 'GET',
params: { id: '' },
res: {
code: 0,
data: {
id: 0,
status: '',
items?: [""], // 可选数组
total: 0,
address: {
city: '',
street: '',
zip: '',
},
},
},
},
}
// ===== 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 刷新
{
"treeNode": {
"value": 0,
"left": { "$meta": { "ref": "/tree#/treeNode" } },
"right": { "$meta": { "ref": "/tree#/treeNode" } },
},
}
使用 $meta.ref 引用自身实现递归类型(树、链表),也可跨文件引用 /filename#/path。
// 替换特定接口的 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 |
三级配置:全局默认 → 实例级 → 单次调用级,灵活控制数据容错策略。
微信小程序 Agent 对 form 类型提供自定义 UTF-8 编码和 boundary 生成。
json2http 是主要工具,从 JSON5 接口配置生成完整的 HTTP 请求代码(Plan、Agent、参数/响应实体类),内置多种 Agent 适配各平台网络库。
json2class 是 json2http 的底层依赖,负责生成实体类代码(fromJson/toJson 等序列化方法),也可独立使用于纯数据模型定义场景。
需要接口请求时直接用 json2http,它会自动包含实体类生成能力。
微信小程序运行在沙箱环境中,不支持 XMLHttpRequest 和 fetch API。Axios 等库需要 polyfill 才能运行,增加包体积和兼容性风险。
typescript_weixin@3 直接封装 wx.request(),零依赖零 polyfill,还支持 require.async() 分包懒加载,是微信小程序的最佳选择。
JSON5 是 JSON 的扩展,支持注释、尾逗号、无引号键名、多行字符串等,更适合人类编写和阅读配置文件。json2http 同时支持 JSON 和 JSON5 格式输入。
在字段名后加 ? 即可声明为可选(nullable)。例如 "email?": "" 生成 email: string | null = null。
数组元素也可标记可选:"items?": ["", null] 表示数组本身可为 null,元素也可为 null。
生成的代码不建议手动修改,因为下次生成会覆盖。推荐通过 JSON 配置调整,或利用 Agent 继承机制扩展功能。json2http 的 Agent 是可替换的,你可以继承 Agent 抽象类实现自定义逻辑。
npx json2class build -l typescript@5dart pub add dev:json2class + dart run json2class build -l dart@3ohpm install json2class --save-dev + ohpm run json2class计划支持 Java 和 Objective-C。当前已支持 Dart@3、ArkTS@12、TypeScript@5、Kotlin@1.3、Swift@5.7 等多种语言。