jsonschema2pojo 基于json schema 生成代码
jsonschema2pojo 是一个很不错的基于jsonschema 生成代码的包以及工具(maven 扩展)
jsonschema2pojo 特点
- 支持基本的jsonschema 操作
- 支持java扩展,比如别名,继承扩展接口
- 外部jsonschema 文件引用
- jsr 303 注解支持
- 自定义时间格式
- 支持基于代码以及maven 扩展使用
代码模式
// 基于jackson-module-jsonSchema 生成schema
ObjectMapper jacksonObjectMapper = new ObjectMapper();
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(jacksonObjectMapper);
JsonSchema schema = schemaGen.generateSchema(MyApp.class);
String schemaString = jacksonObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
System.out.println(schemaString);
// 基于上边的jsonschema 生成代码
JCodeModel codeModel = new JCodeModel();
GenerationConfig config = new DefaultGenerationConfig() {
@Override
public boolean isGenerateBuilders() { // set config option by overriding method
return true;
}
};
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(codeModel, "Mydemo", "com.appdemo", schemaString);
codeModel.build(Files.createDirectory(Paths.get("demo")).toFile());
maven 扩展模式
支持自定义信息,比如包名,生成builder 模式的java 类
<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>1.1.2</version>
<configuration>
<sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
<targetPackage>com.dalong.types</targetPackage>
<generateBuilders>true</generateBuilders>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
说明
openmetadata 比较依赖jsonschema2pojo 生成代码,是一个值得参考学习的项目,使用好jsonschema2pojo 可以加速我们项目的开发
参考资料
https://www.jsonschema2pojo.org/
https://github.com/joelittlejohn/jsonschema2pojo/wiki/Getting-Started
https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2021-10-06 扩展cloud-git 支持基于s3的git repo 管理的参考实现
2021-10-06 express Graceful Shutdown 的几种方法
2021-10-06 基于开源工具提供real time api 的一个参考集成方案
2021-10-06 danfojs 类似pandas 的js 数据分析框架
2021-10-06 cube cloud 集成git 部署模式的一个说明
2021-10-06 cloud-git 开发一个git server 试用
2021-10-06 garfish来自字节跳动的微前端框架