从json自动生成pojo

本文最后更新于:2023年4月15日 晚上

前言

一直以来解析不确定的json对于java来说就是件麻烦事, 如果预先构建好一堆pojo, 需求变来变去的改起来相当烦躁, 于是我之前一直用fastJson库手动写解析逻辑, 没有建立pojo对象, 这样遇到简单的需求还好, 直到我今天修改了一个长达400行的json对象…..

那酸爽就像:

1
JSONObject obj = obj.getJSONObject("asdf").getJSONArray("asdf").getJSONObject(0).getJSONObject("asdfg").getJSONObject("asdfa").getJSONArray("asd").getJSONArray(0).getJSONObject("faaaa");

而且写这些取值都是完全没有提示的, 写的整个人都麻了

于是想有没有什么办法能构建一个”临时”的POJO, 来辅助解析的代码编写

首先我google: online json to pojo

然后找到个网站: https://www.jsonschema2pojo.org/

发现可以直接导入json文本, 通过配置package名称之类的导出一个包含多个pojo类的zip

试了试完美解决了我的400行JSON解析工作…

jsonchema2pojo-maven-plugin

由于上面的过程还是需要手动登录到在线平台转换再导入到项目里, 还是比较麻烦, 看了看它的github发现有maven-plugin

https://github.com/joelittlejohn/jsonschema2pojo

配置文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<build>
<plugins>
<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>1.1.2</version>
<configuration>
<sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
<targetPackage>top.roccoshi.demo.schema</targetPackage>
<sourceType>json</sourceType>
<annotationStyle>none</annotationStyle>
<includeGeneratedAnnotation>false</includeGeneratedAnnotation>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

将json源文件放在对应schema文件的位置

运行mvn generate-sources

即可在target/generated-sources/top/roccoshi/demo/schema/下生成相关的POJO了, 上述配置可以自动生成toString, getter, setter, hashCode, equals这些方法

如果需要基于json schema文件而不是源json文件, 可以将sourceType改为jsonschema

更多配置项, 比如如何生成带有有参构造函数的pojo, 请参考官方文档:

idea不识别target

如果你发现主程序中导入不了target生成的文件, 很有可能是你没将该文件标记为generated source root

可以右键项目根文件夹 => Maven => Generate Sources and Update Folders解决


从json自动生成pojo
https://blog.roccoshi.top/posts/59319/
作者
RoccoShi
发布于
2022年8月20日
许可协议