在 Java Maven 项目中,如何从 JSON 生成 java 源文件?例如我们有
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York"
}
}
当我们运行 mvn generate-sources
时,我们希望它生成如下内容:
class Address {
JSONObject mInternalJSONObject;
Address (JSONObject json){
mInternalJSONObject = json;
}
String getStreetAddress () {
return mInternalJSONObject.getString("streetAddress");
}
String getCity (){
return mInternalJSONObject.getString("city");
}
}
class Person {
JSONObject mInternalJSONObject;
Person (JSONObject json){
mInternalJSONObject = json;
}
String getFirstName () {
return mInternalJSONObject.getString("firstName");
}
String getLastName (){
return mInternalJSONObject.getString("lastName");
}
Address getAddress (){
return Address(mInternalJSONObject.getString("address"));
}
}
作为一名 Java 开发人员,我需要在 pom.xml
中编写哪些 XML 行才能实现这一点?
最佳答案
试试 http://www.jsonschema2pojo.org
或者 Maven 的 jsonschema2pojo 插件:
<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>1.0.2</version>
<configuration>
<sourceDirectory>${basedir}/src/main/resources/schemas</sourceDirectory>
<targetPackage>com.myproject.jsonschemas</targetPackage>
<sourceType>json</sourceType>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
<sourceType>json</sourceType>
涵盖源为 json 的情况(如 OP)。如果您有实际的 json 架构,请删除此行。
2014 年更新:自 09 年 12 月提出此问题以来发生了两件事:
JSON Schema spec已经前进了很多。它仍处于草稿阶段(未定稿),但已接近完成,现在是指定结构规则的可行工具
我最近启动了一个新的开源项目,专门用于解决您的问题:jsonschema2pojo . jsonschema2pojo 工具采用 json 模式文档并生成 DTO 样式的 Java 类(以 .java 源文件的形式)。该项目尚未成熟,但已经涵盖了 json 模式中最有用的部分。我正在寻找用户的更多反馈,以帮助插入开发。现在您可以从命令行或作为 Maven 插件使用该工具。
希望这会有所帮助!
https://stackoverflow.com/questions/1957406/