从 JSON 生成 Java 类?

2023-12-26

在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 开发人员,我需要在我的程序中编写哪些 XML 行?pom.xml为了实现这一目标?


Try http://www.jsonschema2pojo.org http://www.jsonschema2pojo.org

Or the jsonschema2pojoMaven 插件:

<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>

The <sourceType>json</sourceType>涵盖源为 json 的情况(如 OP)。如果你有实际的 jsonschemas,删除这一行。

2014 年更新:自 2009 年 12 月提出此问题以来,发生了两件事:

  • The JSON 模式规范 http://json-schema.org已经发生了很大的变化。它仍处于草案阶段(未最终确定),但已接近完成,现在是指定结构规则的可行工具

  • 我最近启动了一个新的开源项目,专门用于解决您的问题:jsonschema2pojo https://github.com/joelittlejohn/jsonschema2pojo。 jsonschema2pojo 工具采用 json 架构文档并生成 DTO 样式的 Java 类(以 .java 源文件的形式)。该项目尚未成熟,但已经涵盖了 json 模式最有用的部分。我正在寻找用户的更多反馈来帮助推动开发。现在您可以从命令行使用该工具或将其作为 Maven 插件使用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 JSON 生成 Java 类? 的相关文章

随机推荐