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

后端 未结 6 2035
暖寄归人
暖寄归人 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条回答
  •  旧时难觅i
    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;
    }
    

提交回复
热议问题