1.说明

jsonschema2pojo工具可以从JSON Schema(或示例JSON文件)生成Java类型,
并且可以配置生成Jackson 1.x,Jackson 2.x, Moshi 1.x或者Gson库的注解。
支持将jsonschema2pojo作为Maven插件、Ant任务、命令行工具、
Gradle插件或嵌入到Java应用程序中。
本文仅介绍Maven插件使用方式。
另外该工具还提供了在线版本,
可以在网站上直接使用:jsonschema2pojo online

2.创建Maven工程

Eclipse -> File -> New -> Other... -> Maven -> Maven Project
创建一个简单Maven工程,
pom.xml如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>edu.yuwen.util</groupId><artifactId>json-file</artifactId><version>0.0.1-SNAPSHOT</version></parent><artifactId>generate-jsonschema2pojo</artifactId><description>jsonschema2pojo generates Java types from JSON Schema (or example JSON)</description>
</project>

3.引入Maven插件

Maven方式生成Java类需要jsonschema2pojo-maven-plugin,
在pom.xml引入这个插件:

<build><plugins><plugin><groupId>org.jsonschema2pojo</groupId><artifactId>jsonschema2pojo-maven-plugin</artifactId><version>1.0.2</version><configuration><sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory><targetPackage>com.example.types</targetPackage></configuration><executions><execution><goals><goal>generate</goal></goals></execution></executions></plugin></plugins>
</build>

里面的配置项指定了JSON schema文件的目录,
以及生成的Java类的包路径。

4.新建JSON Schema

在src/main/resources/schema目录下
新建JSON Schema文件address.schema.json:

{"$id": "https://example.com/address.schema.json","$schema": "http://json-schema.org/draft-07/schema#","description": "An address similar to http://microformats.org/wiki/h-card","type": "object","properties": {"post-office-box": {"type": "string"},"extended-address": {"type": "string"},"street-address": {"type": "string"},"locality": {"type": "string"},"region": {"type": "string"},"postal-code": {"type": "string"},"country-name": {"type": "string"}},"required": [ "locality", "region", "country-name" ],"dependencies": {"post-office-box": [ "street-address" ],"extended-address": [ "street-address" ]}
}

5.运行Maven插件

运行Maven命令,
执行插件功能:
mvn generate-sources
或者
mvn package
Maven执行成功后,
会生成target/generated-sources/jsonschema2pojo/com/example/types/Address.java类。
推荐使用mvn generate-sources,
这样生成的target目录更干净些。

6.查看Address.java

package com.example.types;import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;/*** An address similar to http://microformats.org/wiki/h-card* */
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"post-office-box","extended-address","street-address","locality","region","postal-code","country-name"
})
public class AddressSchema {@JsonProperty("post-office-box")private String postOfficeBox;@JsonProperty("extended-address")private String extendedAddress;@JsonProperty("street-address")private String streetAddress;/*** * (Required)* */@JsonProperty("locality")private String locality;/*** * (Required)* */@JsonProperty("region")private String region;@JsonProperty("postal-code")private String postalCode;/*** * (Required)* */@JsonProperty("country-name")private String countryName;@JsonIgnoreprivate Map<String, Object> additionalProperties = new HashMap<String, Object>();@JsonProperty("post-office-box")public String getPostOfficeBox() {return postOfficeBox;}@JsonProperty("post-office-box")public void setPostOfficeBox(String postOfficeBox) {this.postOfficeBox = postOfficeBox;}@JsonProperty("extended-address")public String getExtendedAddress() {return extendedAddress;}@JsonProperty("extended-address")public void setExtendedAddress(String extendedAddress) {this.extendedAddress = extendedAddress;}@JsonProperty("street-address")public String getStreetAddress() {return streetAddress;}@JsonProperty("street-address")public void setStreetAddress(String streetAddress) {this.streetAddress = streetAddress;}/*** * (Required)* */@JsonProperty("locality")public String getLocality() {return locality;}/*** * (Required)* */@JsonProperty("locality")public void setLocality(String locality) {this.locality = locality;}/*** * (Required)* */@JsonProperty("region")public String getRegion() {return region;}/*** * (Required)* */@JsonProperty("region")public void setRegion(String region) {this.region = region;}@JsonProperty("postal-code")public String getPostalCode() {return postalCode;}@JsonProperty("postal-code")public void setPostalCode(String postalCode) {this.postalCode = postalCode;}/*** * (Required)* */@JsonProperty("country-name")public String getCountryName() {return countryName;}/*** * (Required)* */@JsonProperty("country-name")public void setCountryName(String countryName) {this.countryName = countryName;}@JsonAnyGetterpublic Map<String, Object> getAdditionalProperties() {return this.additionalProperties;}@JsonAnySetterpublic void setAdditionalProperty(String name, Object value) {this.additionalProperties.put(name, value);}@Overridepublic String toString() {StringBuilder sb = new StringBuilder();sb.append(AddressSchema.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');sb.append("postOfficeBox");sb.append('=');sb.append(((this.postOfficeBox == null)?"<null>":this.postOfficeBox));sb.append(',');sb.append("extendedAddress");sb.append('=');sb.append(((this.extendedAddress == null)?"<null>":this.extendedAddress));sb.append(',');sb.append("streetAddress");sb.append('=');sb.append(((this.streetAddress == null)?"<null>":this.streetAddress));sb.append(',');sb.append("locality");sb.append('=');sb.append(((this.locality == null)?"<null>":this.locality));sb.append(',');sb.append("region");sb.append('=');sb.append(((this.region == null)?"<null>":this.region));sb.append(',');sb.append("postalCode");sb.append('=');sb.append(((this.postalCode == null)?"<null>":this.postalCode));sb.append(',');sb.append("countryName");sb.append('=');sb.append(((this.countryName == null)?"<null>":this.countryName));sb.append(',');sb.append("additionalProperties");sb.append('=');sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));sb.append(',');if (sb.charAt((sb.length()- 1)) == ',') {sb.setCharAt((sb.length()- 1), ']');} else {sb.append(']');}return sb.toString();}@Overridepublic int hashCode() {int result = 1;result = ((result* 31)+((this.postOfficeBox == null)? 0 :this.postOfficeBox.hashCode()));result = ((result* 31)+((this.streetAddress == null)? 0 :this.streetAddress.hashCode()));result = ((result* 31)+((this.postalCode == null)? 0 :this.postalCode.hashCode()));result = ((result* 31)+((this.locality == null)? 0 :this.locality.hashCode()));result = ((result* 31)+((this.countryName == null)? 0 :this.countryName.hashCode()));result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));result = ((result* 31)+((this.extendedAddress == null)? 0 :this.extendedAddress.hashCode()));result = ((result* 31)+((this.region == null)? 0 :this.region.hashCode()));return result;}@Overridepublic boolean equals(Object other) {if (other == this) {return true;}if ((other instanceof AddressSchema) == false) {return false;}AddressSchema rhs = ((AddressSchema) other);return (((((((((this.postOfficeBox == rhs.postOfficeBox)||((this.postOfficeBox!= null)&&this.postOfficeBox.equals(rhs.postOfficeBox)))&&((this.streetAddress == rhs.streetAddress)||((this.streetAddress!= null)&&this.streetAddress.equals(rhs.streetAddress))))&&((this.postalCode == rhs.postalCode)||((this.postalCode!= null)&&this.postalCode.equals(rhs.postalCode))))&&((this.locality == rhs.locality)||((this.locality!= null)&&this.locality.equals(rhs.locality))))&&((this.countryName == rhs.countryName)||((this.countryName!= null)&&this.countryName.equals(rhs.countryName))))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.extendedAddress == rhs.extendedAddress)||((this.extendedAddress!= null)&&this.extendedAddress.equals(rhs.extendedAddress))))&&((this.region == rhs.region)||((this.region!= null)&&this.region.equals(rhs.region))));}}

7.引入插件依赖

当把Address.java放到工程的src/main/java目录下时,
Java编译会报错,
这是因为生成的类型依赖于Commons Lang的equals、hashCode和toString。
一些模式结构也会以Jackson注释的形式产生解析器提示。
需要在pom.xml中添加必要的依赖:

<dependencies><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.4</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.5.4</version></dependency>
</dependencies>

8.新建JSON文件

上面演示了从JSON Schema生成Java类,
下面演示从JSON文件生成Java类,
首先在src\main\resources\json目录下,
新建一个JOSN文件person.json:

{"name":"bob","age":33
}

9.修改插件配置

主要是指定了sourceType和sourceDirectory,
指定了源文件的格式是json和所在目录。

<build><plugins><plugin><groupId>org.jsonschema2pojo</groupId><artifactId>jsonschema2pojo-maven-plugin</artifactId><version>1.0.2</version><configuration><sourceType>json</sourceType><sourceDirectory>${basedir}/src/main/resources/json</sourceDirectory><outputDirectory>${basedir}/src/main/java</outputDirectory><targetPackage>com.example.types</targetPackage><addCompileSourceRoot>true</addCompileSourceRoot><annotationStyle>jackson2</annotationStyle></configuration><executions><execution><goals><goal>generate</goal></goals></execution></executions></plugin></plugins>
</build>

10.生成Person.java类

mvn generate-sources执行成功后,
会生成src/main/java/com/example/types/Person.java:

package com.example.types;import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"name","age"
})
public class Person {@JsonProperty("name")private String name;@JsonProperty("age")private Integer age;@JsonIgnoreprivate Map<String, Object> additionalProperties = new HashMap<String, Object>();@JsonProperty("name")public String getName() {return name;}@JsonProperty("name")public void setName(String name) {this.name = name;}@JsonProperty("age")public Integer getAge() {return age;}@JsonProperty("age")public void setAge(Integer age) {this.age = age;}@JsonAnyGetterpublic Map<String, Object> getAdditionalProperties() {return this.additionalProperties;}@JsonAnySetterpublic void setAdditionalProperty(String name, Object value) {this.additionalProperties.put(name, value);}@Overridepublic String toString() {StringBuilder sb = new StringBuilder();sb.append(Person.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');sb.append("name");sb.append('=');sb.append(((this.name == null)?"<null>":this.name));sb.append(',');sb.append("age");sb.append('=');sb.append(((this.age == null)?"<null>":this.age));sb.append(',');sb.append("additionalProperties");sb.append('=');sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));sb.append(',');if (sb.charAt((sb.length()- 1)) == ',') {sb.setCharAt((sb.length()- 1), ']');} else {sb.append(']');}return sb.toString();}@Overridepublic int hashCode() {int result = 1;result = ((result* 31)+((this.name == null)? 0 :this.name.hashCode()));result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));result = ((result* 31)+((this.age == null)? 0 :this.age.hashCode()));return result;}@Overridepublic boolean equals(Object other) {if (other == this) {return true;}if ((other instanceof Person) == false) {return false;}Person rhs = ((Person) other);return ((((this.name == rhs.name)||((this.name!= null)&&this.name.equals(rhs.name)))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.age == rhs.age)||((this.age!= null)&&this.age.equals(rhs.age))));}
}

11.插件配置项说明

  1. sourceType:两个可选值,JSON Schema或者JSON文件,默认为JSON Schema。
  2. sourceDirectory:源文件所在的目录,会将该目录下所有文件进行转换,不支持指定单个文件,如果不想全部转换,可以添加一个excludes节点。
  3. outputDirectory:生成Java Pojo类的(根)目录,生成Java类的目录为此目录+包目录,默认值为target/generated-sources/jsonschema2pojo。
  4. targetPackage:生成的Java pojo类的包路径。
  5. addCompileSourceRoot:是否将输出目录作为项目的源码根目录。
  6. annotationStyle:生成的(字段)注解样式,五个可选值:jackson1、jackson2、gson、moshi1和none,默认是jackson2,如果fastjson等工具不支持的,需要设置为none。

更多配置项的使用请参考:jsonschema2pojo-maven-plugin Optional Parameters

12.参考文章

使用maven根据JSON文件自动生成Java POJO类(Java Bean)源文件jsonschema2pojo github


http://www.taodudu.cc/news/show-1250966.html

相关文章:

  • YangTools从YANG生成Java类(Maven)
  • GitBash添加tree命令
  • SpringBoot集成Maven工程
  • SpringBoot开发Restful接口
  • Notepad++便签模式
  • SpringBoot集成Cache缓存(Ehcache缓存框架,注解方式)
  • PowerDesigner生成数据库刷库脚本
  • PowerDesigner生成数据库设计文档
  • Eclipse配置国内镜像源
  • PingInfoView批量PING工具
  • Git合并两个不同的仓库
  • Guava事件处理组件Eventbus使用入门
  • Junit4集成到Maven工程
  • Redis集成到Maven工程(Jedis客户端)
  • SpringBoot集成Cache缓存(Redis缓存,RedisTemplate方式)
  • Junit5集成到Maven工程
  • Junit5集成到SpringBoot工程
  • 语言代码表
  • Protobuf生成Java代码(Maven)
  • Protobuf生成Java代码(命令行)
  • Maven查看插件信息
  • SpringBoot脚手架工程快速搭建
  • SpringBoot集成MyBatis-Plus分页插件
  • SNMP客户端工具MIB Browser
  • PowerDesigner运行自定义VBS脚本,复制Name到Comment
  • BitMap-BitSet(JDK1.8)基本使用入门
  • IDEA查看Java类的UML关系图
  • 30. 包含min函数的栈
  • 35. 复杂链表的复制
  • 58 - II. 左旋转字符串

Jsonschema2pojo从JSON生成Java类(Maven)相关推荐

  1. YangTools从YANG生成Java类(Maven)

    1.说明 ODL提供了Yang Tools工具从YANG文件生成Java类, 本文介绍使用Maven插件的方式生成, 基于yang-maven-plugin这个插件. 2.创建Maven工程 Ecli ...

  2. jaxb 生成java类_重用生成的JAXB类

    jaxb 生成java类 在本文中,我将演示如何利用XJC扩展来重用以前从XML模式生成的类. 当其他XML架构导入XML架构并且您不想每次都生成相同的类时,这很有用. 导入的架构(Product.x ...

  3. xsd 生成 java 类_如何从Java类生成XSD

    xsd 生成 java 类 In last few posts, we learned about Java JAXB and how to generate java class from XSD. ...

  4. jaxb-xjc.jar_jaxb2-maven-plugin XJC示例,用于从XSD生成Java类

    jaxb-xjc.jar Today we will look into jaxb2-maven-plugin XJC example to generate java classes from XS ...

  5. 使用Protobuf文件一键生成Java类

    使用Protobuf文件生成Java类 .proto 文件生成 .java 参考 看了一篇文章:主题是 proto 先生成 desc,然后在用 FreeMarker 模板引擎来做代码自动生成了: .p ...

  6. PowerDesigner如何将物理模型转为对象模型,将对象模型转生成Java类

    问题:PowerDesigner如何将物理模型转为对象模型,将对象模型转生成Java类 解决:物理模型转对象模型 注:勾选一下选项 解决:将对象模型转为Java类 核对后点击"确定" ...

  7. java 生成 xml dtd_使用DTD文件中的JAXB生成Java类 – 如何修改DTD?

    在他的回答中,mavrav似乎告诉DTD这是不可能的.我不太清楚如何使用DTD. 但是,如果可以,请在XML模式中翻译您的DTD. 我试着用这个谢玛: xmlns:hr="http://my ...

  8. Eclipse 插件用法:Eclipse 利用 Amateras UML 生成 Java 类图、时序图和 UML 类图

    文章目录 前言 一.安装 Eclipse 官方提供的安装框架 GEF 1.1.Eclipse 中第三方插件更新/安装策略 1.2.为什么选择 GEF 框架? 1.3.GEF 框架安装 二.安装 Ama ...

  9. gradle生成java文件_使用Gradle for Java插件生成Java类

    我想使用Gradle任务为 Java 项目生成Java类,类似于Android插件如何BuildConfig.java使用buildConfig 表示法创建,例如: android { ... bui ...

最新文章

  1. 隐藏Nginx版本号的安全性与方法
  2. word 转html utf8 在线_pdf转word在线转换器:办公必备工具安利!
  3. angularJS 表单验证
  4. Redis学习笔记之入门基础知识——简介
  5. HBase上关于CMS、GC碎片、大缓存的一种解决方案:Bucket Cache
  6. 关于substring的理解
  7. 当SQLServer判断不等于遇到null的时候
  8. c#中的委托、事件、Func、Predicate、Observer设计模式以及其他
  9. 上瘾:如何打造习惯养成中的产品(投资篇)
  10. 查看vs支持的c#语言版本/查看.NetCore版本/更改c#语言版本
  11. UG NX10.0 软件安装教程
  12. Golang优化之内存对齐
  13. Iometer存储测试工具参数说明-5 存储规格选项
  14. html用bmob做留言,Bmob 之 简单使用
  15. java copy-on-write_COW奶牛!Copy On Write机制了解一下
  16. 如何进行软件系统架构设计?
  17. 当docker pull mysql时,一直Waiting,很多等待,报:error pulling image configuration
  18. html背景图片不重叠铺满,html中背景图片铺满页面没有重复的效果
  19. PPT文字很多的排版,PPT图片很多的排版,PPT图文排版
  20. Batch Normalization (BN层)-----批归一化

热门文章

  1. [spring boot]idea中实现热部署的方法
  2. 数组对象的过滤(取出一项中的某些字段)
  3. Lua学习笔记(5): 表
  4. react+redux+antd图书管理系统学习
  5. asp.net的处理机制(.ashx/.aspx)
  6. 关于Js下拉导航的解释
  7. new、delete与malloc、free的详解
  8. 决定对SQL Server 2008 R2进行升级
  9. windows核心编程读书笔记(一)
  10. HTML5概述、标签