JSON-RPC2.0规范由JSON-RPC工作组(json-rpc@googlegroups.com)维护,发布于2010-03-26(基于2009-05-24的版本), 最近的更新于2013-01-04。
整体来说,2.0版本的JSON-RPC规范改动的很小,大的改动大概有3点:
[参数1,参数2,,,]
,也可以使用命名参数{key:value}
。终于说清楚了这个批量请求怎么操作,就是一次请求里用数组包装多个请求对象。示例如下,打包5个请求:
--> [
{"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
{"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
{"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
{"foo": "boo"},
{"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"},
{"jsonrpc": "2.0", "method": "get_data", "id": "9"}
]
<-- [
{"jsonrpc": "2.0", "result": 7, "id": "1"},
{"jsonrpc": "2.0", "result": 19, "id": "2"},
{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null},
{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "5"},
{"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"}
]
规范定义了所有的请求应该并发执行,并且返回不保证顺序,客户端自己使用id去匹配对应的请求和响应。而且对于请求的处理中只要有一个出错,则返回一个统一的错误信息(就是不区分哪一条失败,全部都算失败了)。 这个设计看起来是针对事务考虑的,但是在一般的使用场景里应该会比较麻烦。
改进的error机制是,error变成了一个明确定义的对象。包括三个属性:
比原来的粗放型错误机制好多了。
从XML-RPC借来了服务器端的错误代码:
code | message | meaning |
---|---|---|
-32700 | Parse error Invalid | JSON was received by the server. An error occurred on the server while parsing the JSON text. |
-32600 | Invalid Request | The JSON sent is not a valid Request object. |
-32601 | Method not found | The method does not exist / is not available. |
-32602 | Invalid params | Invalid method parameter(s). |
-32603 | Internal error | Internal JSON-RPC error. |
-32000 to -32099 | Server error | Reserved for implementation-defined server-errors. |