一、需求
1、给出特定格式json-schema,生成随机json串
2、json串,目录结构按json-schema定义
3、使用java开发语言
4、不需要提供页面,能输出随机json串即可(控制台打印)
5、json-schema中的结构可能存在多级,属性不确定,但结构统一
二、示例
1、json-schema
{
"definitions": {},
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://example.com/object1646817236.json",
"title": "Root",
"type": "object",
"required": [
"city",
"number",
"gov",
"user"
],
"properties": {
"city": {
"$id": "#root/city",
"title": "City",
"type": "string",
"default": "",
"minLength": 1,
"maxLength": 40
},
"number": {
"$id": "#root/number",
"title": "Number",
"type": "integer",
"minLength": 1,
"maxLength": 6,
"default": 0
},
"gov": {
"$id": "#root/gov",
"title": "Gov",
"type": "object",
"required": [
"adrress",
"personnum"
],
"properties": {
"adrress": {
"$id": "#root/gov/adrress",
"title": "Adrress",
"type": "string",
"default": "",
"minLength": 1,
"maxLength": 40
},
"personnum": {
"$id": "#root/gov/personnum",
"title": "Personnum",
"type": "integer",
"minLength": 1,
"maxLength": 8,
"default": 0
}
}
},
"user": {
"$id": "#root/user",
"title": "User",
"type": "array",
"default": [],
"items":{
"$id": "#root/user/items",
"title": "Items",
"type": "object",
"required": [
"name",
"age"
],
"properties": {
"name": {
"$id": "#root/user/items/name",
"title": "Name",
"type": "string",
"default": "",
"minLength": 1,
"maxLength": 40
},
"age": {
"$id": "#root/user/items/age",
"title": "Age",
"type": "integer",
"minLength": 1,
"maxLength": 4,
"default": 0
}
}
}
}
}
}
2、预期结果
{
"city":"chicago",
"number":20,
"gov":{
"adrress":"chicago",
"personnum":10
},
"user":[
{
"name":"Alex",
"age":20
}
]
}
三、解决方案
1、方案说明
1)度娘搜索的解决方案都不满足,大多数是固定schema,即字段固定
2)csdn上有将schema转java实体bean,也不能拿来用
3)最终决定自行实现
4)考虑快速实现问题,使用maven管理,使用hutool解决常规判断
2、方案依赖
1)jdk8
2)idea
3)maven项目
4)阿里maven库
5)hutool工具依赖
3、方案思路
1)分析结构
属性定义: properties
属性类型: type
取值范围: minLength与maxLength
2)抽取类型,有:object,string,integer,number,array
3)处理分析
object: 拥有子节点
string:生成随机字符串
integer:生成随机数
number: 与integer一致
array:数组,需要单独处理,解析后类型参照string,integer
4)使用递归处理子集结构