0
点赞
收藏
分享

微信扫一扫

jsonschema2pojo 基于json schema 生成代码

jsonschema2pojo 是一个很不错的基于jsonschema 生成代码的包以及工具(maven 扩展)

jsonschema2pojo 特点

  • 支持基本的jsonschema 操作
  • 支持java扩展,比如别名,继承扩展接口
  • 外部jsonschema 文件引用
  • jsr 303 注解支持
  • 自定义时间格式
  • 支持基于代码以及maven 扩展使用

代码模式

//  基于jackson-module-jsonSchema 生成schema

 //  基于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>

<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​​

举报

相关推荐

0 条评论