java 有没有办法从 json 响应创建 bean 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7440212/
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-10-30 19:58:57  来源:igfitidea点击:

Is there a way to create the bean class from a json response

javajsongson

提问by Jason

Converting JSON to Java

将 JSON 转换为 Java

The above question is with reference to what has been described on the above thread. There are so many API(s) which provide the flexibility to return responses either in XML or JSON. **I would like to know if there is a way to automatically construct the java bean corresponding to a JSON response. **

上面的问题是参考上面线程中描述的内容。有很多 API 提供了以 XML 或 JSON 形式返回响应的灵活性。**想知道有没有办法自动构造一个JSON响应对应的java bean。**

采纳答案by Pablo Grisafi

lets say you get an object like

假设你得到一个像

    [
        {
        "name":"Java 6 Greatest Hits",
        "Author":"Jim Bob Jones",
        "price":10.25
        },
        {
        "name":"How to raise a goat",
        "Author":"Sir Paxton",
        "price":55.97   
        },
        {
        "name":"Snow - It is cold",
        "Author":"Dr. White",
        "price":9.99    
        }
   ]

And you want a class like

你想要一个像

public class Book{
    private String author;
    private String name;
    private Number price
}

with getters and setters One option is to use a service like JSONGen, which will create that class. You need to use it first, and include the generated code in your project. Another option could be dynamically generate the class using javassist or CGLib, but that class would be useless unless you use reflection to access its members, so even if it wouldbe a class, it will behavelike a really annoying Map. In no way will be better that simple using JSONObject

使用 getter 和 setter 一种选择是使用像JSONGen这样的服务,它将创建该类。您需要使用它第一,并在项目中包含生成的代码。另一种选择可能是动态生成使用了Javassist或CGLIB的类,但除非你使用反射来访问其成员,所以即使该类将是无用的是一个类,它会表现得就像一个非常恼人的地图。使用JSONObject绝不会这么简单

回答by swanliu

seems a simple Message Type Entity not meet you requirement ?

似乎一个简单的消息类型实体不符合您的要求?

if you want convert a json to an existed and known java bean class,

如果您想将 json 转换为现有的已知 java bean 类,

many lib can do so, like

许多 lib 可以这样做,例如

http://json-lib.sourceforge.net/apidocs/net/sf/json/class-use/JSONObject.html

http://json-lib.sourceforge.net/apidocs/net/sf/json/class-use/JSONObject.html

 JSONObject.toBean(JSONObject jsonObject, Class beanClass)
      Creates a bean from a JSONObject, with a specific target class.

btw, if you are communicating with restful webservice, org.springframework.web.client.RestTemplate will help you get direct bean result insteadof json.

顺便说一句,如果您正在与 restful webservice 通信,org.springframework.web.client.RestTemplate 将帮助您获得直接的 bean 结果而不是 json。

if class does not exists, you need program with java reflect mechanism.try use CGLIB ,http://cglib.sourceforge.net/, dynamic create some class like BeanMap. i wrote a simple sample, but be ware, opearting class byte is hard and you may meet strange trouble with JVM . Strongly not encourage to do so.

如果类不存在,则需要具有 Java 反射机制的程序。尝试使用 CGLIB , http://cglib.sourceforge.net/,动态创建一些像 BeanMap 这样的类。我写了一个简单的示例,但请注意,操作类字节很难,您可能会遇到 JVM 奇怪的问题。强烈不鼓励这样做。

  public static BeanMap generateBean(JSONObject json) {
    BeanGenerator generator = new BeanGenerator();

    Iterator keys = json.keys();

    while (keys.hasNext()) {
        Object key = keys.next();
        Object value = json.get(key);
        Class keyClass = guessValueClass(value);
        generator.addProperty(key.toString(), keyClass);

    }

    Object result = generator.create();
    BeanMap bean = BeanMap.create(result);
    keys = json.keys();

    while (keys.hasNext()) {
        Object key = keys.next();
        Object value = json.get(key);
        bean.put(key, value);
    }

    return bean;
}

/**
 * TODO fix guess
 */
static Class guessValueClass(Object value) {

    try {
        Integer.parseInt(value.toString());
        return Integer.class;
    } catch (NumberFormatException e1) {

    }
    try {
        Double.parseDouble(value.toString());
        return Double.class;
    } catch (NumberFormatException e1) {

    }
    return String.class;
}

回答by Rafael Cordones

I believe the main issue here is that the JSON response lacks type informationand last time I checked :-) in Java you need to declare the type of a class property. So some heuristics will be needed to infer the type form the value in the JSON response.

我相信这里的主要问题是 JSON 响应缺少类型信息,上次我检查 :-) 在 Java 中,您需要声明类属性的类型。因此需要一些启发式方法来推断 JSON 响应中的值的类型。

For a related question here in SO have a look at: Generate Java class from JSON?

对于 SO 中的相关问题,请查看:Generate Java class from JSON?

回答by chubbsondubs

回答by Daniel

If you're wanting to generate Java classes from JSON, perhaps you could try Hymanson. It provides a lot of JSON-related functionality, including the ability to generate bytecode from arbitrary JSON. See this blog postfor details.

如果您想从 JSON 生成 Java 类,也许您可​​以尝试Hymanson。它提供了许多与 JSON 相关的功能,包括从任意 JSON 生成字节码的能力。有关详细信息,请参阅此博客文章

回答by Astav

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

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

https://bitbucket.org/astav/jsontojava/wiki/Home

https://bitbucket.org/astav/jsontojava/wiki/Home

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 类,如果它可以反序列化为这些结构,就会这样做 当存在不明确的情况时会提示用户输入