摘要

记录一下实现将JSON转换为Java实体的小工具。

正文

对接方提供了一个70MB的JSON文件给我,我要针对这些数据做数据分析。但是由于数据太大,通过人眼去识别JSON的结构太麻烦了。

于是就找到了一款开源工具joelittlejohn/jsonschema2pojo,它支持将JSON结构或者JSON数据自动生成Java实体。

支持多种方式

具体可以查阅官方文档Getting Started · joelittlejohn/jsonschema2pojo Wiki

本文以Maven插件为例,介绍该工具的使用。

  • java: 1.8
  • maven: 3.6.3

pom.xml

xml
 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
<plugin>
    <groupId>org.jsonschema2pojo</groupId>
    <artifactId>jsonschema2pojo-maven-plugin</artifactId>
    <version>1.2.1</version>
    <configuration>
        <sourceDirectory>${basedir}/json</sourceDirectory>
        <!--指定生成的java所在目录-->
        <outputDirectory>${basedir}/src/main/java</outputDirectory>
        <!--指定java的包名-->
        <targetPackage></targetPackage>
        <sourceType>json</sourceType>
        <annotationStyle>none</annotationStyle>
        <includeGeneratedAnnotation>false</includeGeneratedAnnotation>
        <!--使用基本类型-->
        <usePrimitives>false</usePrimitives>
        <includeGetters>false</includeGetters>
        <includeSetters>false</includeSetters>
        <includeToString>false</includeToString>
        <includeAdditionalProperties>false</includeAdditionalProperties>
        <includeHashcodeAndEquals>false</includeHashcodeAndEquals>
        <includeConstructors>false</includeConstructors>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

然后执行命令mvn clean compile即可。

示例代码meethigher/json2entity: 基于jsonschema2pojo-maven-plugin插件实现的json转换entity代码示例