在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://htmlpreview.github.io/?https://raw.githubusercontent.com/foobnix/android-universal-utils/master/json/generator.html

{
    "auctionHouse": "sample string 1",
    "bidDate": "2014-05-30T08:20:38.5426521-04:00 ",
    "bidPrice": 3,
    "bidPrice1": 3.1,
    "isYear":true
}

结果Java类

private String  auctionHouse;
private Date  bidDate;
private int  bidPrice;
private double  bidPrice1;
private boolean  isYear;

JSONObject get

auctionHouse = obj.getString("auctionHouse");
bidDate = obj.opt("bidDate");
bidPrice = obj.getInt("bidPrice");
bidPrice1 = obj.getDouble("bidPrice1");
isYear = obj.getBoolean("isYear");

JSONObject put

obj.put("auctionHouse",auctionHouse);
obj.put("bidDate",bidDate);
obj.put("bidPrice",bidPrice);
obj.put("bidPrice1",bidPrice1);
obj.put("isYear",isYear);

其他回答

我知道这是一个老问题,但我是在自己试图寻找答案的时候偶然发现的。

答案中提到了在线json-pojo生成器(jsongen),这很好,但我需要一些可以在命令行上运行并进行更多调整的东西。

因此,我编写了一个非常粗糙的ruby脚本来获取一个示例JSON文件并从中生成pojo。它有许多限制(例如,它不处理与java保留关键字匹配的字段),但在许多情况下它已经足够了。

默认情况下,生成的代码对Jackson进行注释,但可以通过开关关闭。

你可以在github上找到代码:https://github.com/wotifgroup/json2pojo

添加到@japher的帖子。如果您不是特别依赖于JSON,那么Protocol Buffers值得一试。

我创建了一个github项目Json2Java来做这件事。 https://github.com/inder123/json2java

Json2Java提供了重命名字段和创建继承层次结构等定制。

我用这个工具创建了一些相对复杂的api:

Gracenote的TMS API: https://github.com/inder123/gracenote-java-api

谷歌地图地理编码API: https://github.com/inder123/geocoding

试试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年更新:自2009年12月提出这个问题以来,发生了两件事:

The JSON Schema spec has moved on a lot. It's still in draft (not finalised) but it's close to completion and is now a viable tool specifying your structural rules I've recently started a new open source project specifically intended to solve your problem: jsonschema2pojo. The jsonschema2pojo tool takes a json schema document and generates DTO-style Java classes (in the form of .java source files). The project is not yet mature but already provides coverage of the most useful parts of json schema. I'm looking for more feedback from users to help drive the development. Right now you can use the tool from the command line or as a Maven plugin.

据我所知,没有这样的工具。然而。

我怀疑,主要原因是,不像XML(它有XML Schema,然后像“xjc”这样的工具可以在XML和POJO定义之间做你想做的事情),没有完全特性的模式语言。有JSON Schema,但是它很少支持实际的类型定义(主要关注JSON结构),所以生成Java类会很棘手。但是可能仍然是可能的,特别是如果定义并使用一些命名约定来支持生成的话。

然而,这是一些相当频繁的要求(在我所关注的JSON工具项目的邮件列表中),所以我认为在不久的将来会有人编写这样的工具。

所以我不认为它本身是一个坏主意(而且:它对所有用例都不是一个好主意,这取决于你想做什么)。