json schema 定义了 json 内容的格式及约束, 是 API 管理平台生成 API 文档的重要依据;
json 的基础知识
json 的类型:
- string
- number (包含整型 / 浮点型)
- object
- array
- boolean
- null
json schema 典型例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| { "request":{ "type":"object", "description":"request parameters schema", "properties":{ "online":{ "type":"boolean", "default":false }, "users":{ "type":"array", "items":{ "type":"object", "properties":{ "id":{ "type":"number" }, "nick":{ "type":"string", "default": "visitor" } }, "required":[ "id" ] } }, "message":{ "type":"object", "default":"{}", "properties":{ "attributes":{ "type":"object", "additionalProperties":{ "type":"string" } }, "msgId":{ "type":"string", "default":"testId" }, "sendTime":{ "type":"string" } }, "required":[ "msgId", "attributes" ] } }, "required":[ "message", "online" ] }, "response":{ "type":"object", "description":"response parameters schema", "additionalProperties":{ "type":"object", "properties":{ "user":{ "type":"string" }, "value":{ "type":"number", "default":10 } } } } }
|
对应的类定义
以下为一个符合上述 json schema 约束的 java bean:
request 相关类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class UserValueRequest { private boolean online; private List<User> users; private Message message; }
public class User { private int id; private String nick; }
pubblic class Message { private String msgId; private String sendTime; private Map<String, String> attributes; }
|
response 相关类:
1 2 3 4
| public class UserValue { private String user; private int value; }
|
调用方法签名:
1
| Map<String, UserValue> method(UserValueRequest request);
|
参考链接