- 下载 Apifox 软件,作为客户端发送 http post 请求
- 实现服务器代码:用到的三方库代码: cpp-httplib,jsonrpccxx, nlohmman::json
- 需要的c++编译器版本,c17
- 注意客户端发送请求<里面的param参数必须是数组>
数据结构和编解码定义
c++本地方法
json-rpc回调注册:
主要技术点:
1. 模板元编程,将 json对象转为c++函数需要的参数,返回值:json类型
2. 利用 nlohmman::json 的自动转换能力,
假设 method
返回 std::tuple<int, std::string, std::vector<double>>
类型,nlohmann::json
会自动将该 tuple
转换为 JSON 数组,其中:
int
会成为一个 JSON 整数;std::string
会成为一个 JSON 字符串;std::vector<double>
会成为一个 JSON 数组。
测试:
//请求
{
"jsonrpc": "2.0",
"method": "AllProducts",
"params": [],
"id": 1
}
//回复
{
"id": 1,
"jsonrpc": "2.0",
"result": [
{
"category": "order",
"id": "1",
"name": "apple",
"price": 56.2
},
{
"category": "cc",
"id": "2",
"name": "huawei",
"price": 12.2
}
]
}
//请求
{
"jsonrpc": "2.0",
"method": "getInfo",
"params": [1, "wujie", [9.2,3.4,2,1,2]],
"id": 1
}
//回复
{
"id": 1,
"jsonrpc": "2.0",
"result": [
1,
"wujie",
[
9.2,
3.4,
2.0,
1.0,
2.0
]
]
}
//请求
{
"jsonrpc": "2.0",
"method": "AddProduct",
"params": [{
"category": "order",
"id": "3",
"name": "xiaomi",
"price": 44.4
}
],
"id": 1
}
//回复
{
"id": 1,
"jsonrpc": "2.0",
"result": true
}