从 JSON 生成 Java 类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1957406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:46:53  来源:igfitidea点击:

Generate Java class from JSON?

javajson

提问by Denis Palnitsky

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

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

{
  "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.

写起来并不难,但我相信有人已经做到了。

回答by Denis Palnitsky

Thanks all who attempted to help.
For me this script was helpful. It process only flat JSON and don't take care of types, but automate some routine

感谢所有试图提供帮助的人。
对我来说,这个脚本很有帮助。它只处理平面 JSON,不处理类型,但自动化一些例程

  String str = 
        "{"
            + "'title': 'Computing and Information systems',"
            + "'id' : 1,"
            + "'children' : 'true',"
            + "'groups' : [{"
                + "'title' : 'Level one CIS',"
                + "'id' : 2,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Intro To Computing and Internet',"
                    + "'id' : 3,"
                    + "'children': 'false',"
                    + "'groups':[]"
                + "}]" 
            + "}]"
        + "}";



    JSONObject json = new JSONObject(str);
    Iterator<String> iterator =  json.keys();

    System.out.println("Fields:");
    while (iterator.hasNext() ){
       System.out.println(String.format("public String %s;", iterator.next()));
    }

    System.out.println("public void Parse (String str){");
    System.out.println("JSONObject json = new JSONObject(str);");

    iterator  = json.keys();
    while (iterator.hasNext() ){
       String key = iterator.next();
       System.out.println(String.format("this.%s = json.getString(\"%s\");",key,key ));

    System.out.println("}");

回答by StaxMan

As far as I know there is no such tool. Yet.

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

The main reason is, I suspect, that unlike with XML (which has XML Schema, and then tools like 'xjc' to do what you ask, between XML and POJO definitions), there is no fully features schema language. There is JSON Schema, but it has very little support for actual type definitions (focuses on JSON structures), so it would be tricky to generate Java classes. But probably still possible, esp. if some naming conventions were defined and used to support generation.

主要原因是,我怀疑,与 XML(它有 XML 模式,然后是像“xjc”这样的工具来做你所要求的,在 XML 和 POJO 定义之间)不同,没有完全特征的模式语言。有 JSON Schema,但它对实际类型定义的支持很少(专注于 JSON 结构),因此生成 Java 类会很棘手。但可能仍然有可能,尤其是。如果定义了一些命名约定并用于支持生成。

However: this is something that has been fairly frequently requested (on mailing lists of JSON tool projects I follow), so I think that someone will write such a tool in near future.

但是:这是经常被要求的东西(在我关注的 JSON 工具项目的邮件列表中),所以我认为在不久的将来有人会编写这样的工具。

So I don't think it is a bad idea per se (also: it is not a good idea for all use cases, depends on what you want to do ).

所以我认为这本身并不是一个坏主意(另外:对于所有用例来说这不是一个好主意,取决于你想做什么)。

回答by joelittlejohn

Try:

尝试:

http://www.jsonschema2pojo.org

http://www.jsonschema2pojo.org

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.

Orsol,我确定您不会在这里等待解决方案,但是为了下一个找到此线程的人,我想我会添加更多信息。

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

自 09 年 12 月提出此问题以来,发生了两件事:

  • The JSON Schema spechas 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.

  • JSON模式规范已经转移了很多。它仍在草案中(未最终确定),但已接近完成,现在是一个可行的工具,可指定您的结构规则

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

Hope this helps!

希望这可以帮助!

回答by dgorissen

To add to @japher's post. If you are not particularly tied to JSON, Protocol Buffersis worth checking out.

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

回答by Chris R

I'm aware this is an old question, but I stumbled across it while trying to find an answer myself.

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

The answer that mentions the online json-pojo generator (jsongen) is good, but I needed something I could run on the command line and tweak more.

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

So I wrote a very hacky ruby script to take a sample JSON file and generate POJOs from it. It has a number of limitations (for example, it doesn't deal with fields that match java reserved keywords) but it does enough for many cases.

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

The code generated, by default, annotates for use with Hymanson, but this can be turned off with a switch.

默认情况下,生成的代码注释以供 Hymanson 使用,但这可以通过开关关闭。

You can find the code on github: https://github.com/wotifgroup/json2pojo

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

回答by ehanoc

I had the same problem so i decided to start writing a small tool to help me with this. Im gonna share andopen source it.

我遇到了同样的问题,所以我决定开始编写一个小工具来帮助我解决这个问题。我要分享并开源它。

https://github.com/BrunoAlexandreMendesMartins/CleverModels

https://github.com/BrunoAlexandreMendesMartins/CleverModels

It supports, JAVA, C# & Objective-c from JSON .

它支持 JSON 中的 JAVA、C# 和 Objective-c。

Feel free to contribute!

随意贡献!

回答by Antoine Sabot-Durand

Answering this old question with recent project ;-).

用最近的项目回答这个老问题;-)。

At the moment the best solution is probably JsonSchema2Pojo:

目前最好的解决方案可能是JsonSchema2Pojo

It does the job from the seldom used Json Schema but also with plain Json. It provides Ant and Maven plugin and an online test applicationcan give you an idea of the tool. I put a Json Tweet and generated all the containing class (Tweet, User, Location, etc..).

它完成了很少使用的 Json Schema 和普通 Json 的工作。它提供了 Ant 和 Maven 插件,一个在线测试应用程序可以让您了解该工具。我放了一个 Json Tweet 并生成了所有包含类(Tweet、User、Location 等)。

We'll use it on Agoravaproject to generate Social Media mapping and follow the contant evolution in their API.

我们将在Agorava项目中使用它来生成社交媒体映射并跟踪其 API 中的持续演变。

回答by MB.One

You could also try GSON library. Its quite powerful it can create JSON from collections, custom objects and works also vice versa. Its released under Apache Licence 2.0 so you can use it also commercially.

您也可以尝试 GSON 库。它非常强大,它可以从集合、自定义对象创建 JSON,反之亦然。它是在 Apache License 2.0 下发布的,因此您也可以在商业上使用它。

http://code.google.com/p/google-gson/

http://code.google.com/p/google-gson/

回答by Astav

If you're using Hymanson (the most popular library there), try

如果您使用的是 Hymanson(那里最受欢迎的图书馆),请尝试

https://github.com/astav/JsonToJava

https://github.com/astav/JsonToJava

Its open source and anyone should be able to contribute.

它是开源的,任何人都应该能够做出贡献。

Summary

概括

A JsonToJava source class file generator that deduces the schema based on supplied sample json data and generates the necessary java data structures.

一个 JsonToJava 源类文件生成器,它根据提供的示例 json 数据推导出模式并生成必要的 java 数据结构。

It encourages teams to think in Json first, before writing actual code.

它鼓励团队在编写实际代码之前首先考虑 Json。

Features

特征

  • Can generate classes for an arbitrarily complex hierarchy (recursively)
  • Can read your existing Java classes and if it can deserialize into those structures, will do so
  • Will prompt for user input when ambiguous cases exist
  • 可以为任意复杂的层次结构生成类(递归)
  • 可以读取您现有的 Java 类,如果它可以反序列化为这些结构,就会这样做
  • 存在歧义时会提示用户输入

回答by Foobnix

Try my solution

试试我的解决方案

http://htmlpreview.github.io/?https://raw.githubusercontent.com/foobnix/android-universal-utils/master/json/generator.html

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
}

Result Java Class

结果 Java 类

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

JSONObject get

JSONObject 获取

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

JSONObject put

JSONObject 放置

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