从JSON生成Java类? [英] Generate Java class from JSON?

查看:110
本文介绍了从JSON生成Java类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个从JSON生成java源文件的实用程序。例如,我们有

I want a utility that generates java source files from JSON. For example we have

{
  "firstName": "John",  
  "lastName": "Smith",  
  "address": {  
    "streetAddress": "21 2nd Street",  
     "city": "New York"
  }
}

我们将此传递给实用程序,我们希望它生成如下内容:

We pass this to the utility and we want it to generate something like this:

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"));
    }
}

写起来不是很难,但我确定有人已经做到了。

Not so hard to write, but I'm sure somebody already did it.

推荐答案

尝试:

Orsol,我我确定你还没有在这里等待解决方案,但是为了找到这个帖子的下一个人我想我会添加更多信息。

Orsol, I'm sure you're not still waiting for an solution here, but for the sake of the next person that finds this thread I thought I'd add some more info.

自2009年12月问这个问题以来发生了两件事:

Two things have happened since Dec '09 when this question was asked:


  • JSON Schema规范已经发生了很大变化。它仍处于草案阶段(尚未最终确定),但它已接近完成,现在是一个可行的工具,用于指定您的结构规则

  • 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

我最近开始了一个新的开源专门用于解决问题的项目: jsonschema2pojo 。 jsonschema2pojo工具获取json模式文档并生成DTO样式的Java类(以.java源文件的形式)。该项目尚未成熟,但已经提供了对json模式最有用部分的报道。我正在寻找用户的更多反馈,以帮助推动开发。现在你可以从命令行使用该工具或作为Maven插件。

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.

希望这会有所帮助!

这篇关于从JSON生成Java类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆