简体   繁体   English

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

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

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. 有太多的API可以灵活地以XML或JSON形式返回响应。 **I would like to know if there is a way to automatically construct the java bean corresponding to a JSON response. **我想知道是否有一种方法可以自动构造对应于JSON响应的java bean。 ** **

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. getter和setter一个选项是使用像JSONGen这样的服务,它将创建该类。 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 would be a class, it will behave like a really annoying Map. 另一种选择可能是动态生成使用了Javassist或CGLIB的类,但除非你使用反射来访问它的成员,因此,即使这是一个类,它会一个真正讨厌地图该类将是无用的。 In no way will be better that simple using JSONObject 使用JSONObject绝不会更好

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. 如果类不存在,则需要使用java反射机制的程序。 try use CGLIB , http://cglib.sourceforge.net/ , dynamic create some class like BeanMap. 尝试使用CGLIB, http: //cglib.sourceforge.net/,动态创建类似BeanMap的类。 i wrote a simple sample, but be ware, opearting class byte is hard and you may meet strange trouble with JVM . 我写了一个简单的示例,但是要洁具,操作类字节很难,你可能会遇到JVM的奇怪问题。 Strongly not encourage to do so. 强烈不鼓励这样做。

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

I believe the main issue here is that the JSON response lacks type information and last time I checked :-) in Java you need to declare the type of a class property. 我认为这里的主要问题是JSON响应缺少类型信息 ,上次我在Java中检查:-)你需要声明类属性的类型。 So some heuristics will be needed to infer the type form the value in the JSON response. 因此,需要一些启发式来推断JSON响应中值的类型。

For a related question here in SO have a look at: Generate Java class from JSON? 有关SO中的相关问题,请参阅: 从JSON生成Java类?

If you're wanting to generate Java classes from JSON, perhaps you could try Jackson . 如果你想从JSON生成Java类,也许你可以试试Jackson It provides a lot of JSON-related functionality, including the ability to generate bytecode from arbitrary JSON. 它提供了许多与JSON相关的功能,包括从任意JSON生成字节码的能力。 See this blog post for details. 有关详细信息,请参阅此博文

If you're using Jackson (the most popular library there), try 如果您正在使用杰克逊(那里最受欢迎的图书馆),请尝试

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类,如果它可以反序列化到这些结构中,将会这样做当存在模糊情况时将提示用户输入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM