使用jsonschema2pojo-maven-plugin 插件根据json文件生成代码

jsonschema2pojo 是一个不错的工具,可以帮助我们快速的根据json 文件生成pojo代码,提高开发效率,以下为简单的
使用maven 插件进行代码生成

使用maven 插件配置

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <groupId>com.dalong.demo</groupId>
    <artifactId>jsonschemagenerate</artifactId>
    <version>1.0-SNAPSHOT</version>
    <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>

   <build>
       <plugins>
           <plugin>
               <groupId>org.jsonschema2pojo</groupId>
               <artifactId>jsonschema2pojo-maven-plugin</artifactId>
               <version>0.5.1</version>
               <configuration>
                   <sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
                   <targetPackage>com.dalong.app</targetPackage>
                   <sourceType>json</sourceType>
                   <generateBuilders>false</generateBuilders>
               </configuration>
               <executions>
                   <execution>
                       <goals>
                           <goal>generate</goal>
                       </goals>
                   </execution>
               </executions>
           </plugin>
       </plugins>
   </build>
</project>

json 文件

src/main/resources/schema 目录

user.json
{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
}
app.json
{
  "appname": "John",
  "apptag" : "doe",
  "appdescribe"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "applist": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
}

生成代码

mvn  package

说明

jsonschema2pojo 功能比较强大,可以根据yaml xml 等文件格式生成pojo,同时可以方便的为我们生成代码,同时也比较灵活
在api 盛行的时代还是比较好的,同时swagger generator 也是一个不错的选择

生成结果

参考资料

https://github.com/joelittlejohn/jsonschema2pojo/wiki/Getting-Started

posted on 2018-07-17 11:13  荣锋亮  阅读(1313)  评论(0编辑  收藏  举报

导航