irpas技术客

【Java】基于JSON-Schema生成随机JSON的解决方案_hgSuper_java json schema

irpas 4103

一、需求

????????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)使用递归处理子集结构

?4、核心代码处理(示例图)

?5、结果示例图

?6、源码不免费哦

csdn资源-java解析json-schema,生成随机json


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #JAVA #JSON #Schema