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

后端 未结 6 2020
暖寄归人
暖寄归人 2020-12-15 07:42

Converting JSON to 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 t

相关标签:
6条回答
  • 2020-12-15 08:09

    Yes check out http://flexjson.sourceforge.net

    0 讨论(0)
  • 2020-12-15 08:12

    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. So some heuristics will be needed to infer the type form the value in the JSON response.

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

    0 讨论(0)
  • 2020-12-15 08:16

    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 would be a class, it will behave like a really annoying Map. In no way will be better that simple using JSONObject

    0 讨论(0)
  • 2020-12-15 08:18

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

    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.

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

    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

    0 讨论(0)
  • 2020-12-15 08:23

    seems a simple Message Type Entity not meet you requirement ?

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

    many lib can do so, like

    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.

    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.

      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;
    }
    
    0 讨论(0)
  • 2020-12-15 08:24

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

    0 讨论(0)
提交回复
热议问题