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

posted on   荣锋亮  阅读(739)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用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来自字节跳动的微前端框架

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示