Json Series II json to bean (detailed explanation of the JSONObject class) and jsonjsonobject
Method 1/*** Creates a JSONDynaBean from a JSONObject. */public static Object toBean (JSONObject jsonObject) returned data type is obviously not our common data type method 2/*** Creates a bean from a JSONObject, with a specific target class. <br> */public static Object toBean (JSONObject jsonObject, Class beanClass) method 3 (commonly used)/*** Creates a bean from a JSONObject, with a specific target class. <br> * If beanClass is null, this method will re Turn a graph of DynaBeans. any * attribute that is a JSONObject and matches a key in the classMap will be * converted to that target class. <br> * The classMap has the following conventions: * <ul> * <li> Every key must be an String. </li> * <li> Every value must be a Class. </li> * <li> A key may be a regular expression. </li> * </ul> */public static Object toBean (JSONObject jsonObject, Class beanClas S, Map classMap) Method 4/*** Creates a bean from a JSONObject, with the specific configuration. */public static Object toBean (JSONObject jsonObject, JsonConfig jsonConfig) method 2 actually calls Method 4. It seems that the jsonConfig Object is very important and determines the final returned data type, of course, it is far from that. Method 3 finally calls Method 4 Method 5 (commonly used)/*** Creates a bean from a JSONObject, with the specific configuration. */public static Object toBean (JSONObject jsonObject, Object root, JsonConfig jsonConfig) directly processes existing objects and writes json data to existing objects. Common Methods 3 and 5 examples: the bean to json code // The second json to object JSONObject jsonObject = JSONObject. fromObject (returnString); Object returnObject = null; // method 1 class + map config method 3 Map config = new HashMap (); config. put ("addresses", Address. class); config. put ("sameTest", Person. class); returnObject = JSONObject. toBean (jsonObject, Person. class, config); System. out. println (returnObject); // method 2 object + JsonConfig Method 5 P = new Person (); JsonConfig jc = new JsonConfig (); jc. setClassMap (config); jc. terminate (new NewBeanInstanceStrategy () {@ Overridepublic Object newInstance (Class target, JSONObject source) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, InvocationTargetException {if! = Null) {if (target. getName (). equals (Map. class. getName () {return new HashMap ();} return NewBeanInstanceStrategy. DEFAULT. newInstance (target, source);} return null ;}}); JSONObject. toBean (jsonObject, p, jc); System. out. println (p. getAddresses (). get (0 ). getAddress ());