Net.sf.json.JSONObject provides us with a Tobean method for converting to Java objects, which is much more powerful, with the use of the JDK's reflection mechanism as a simple helper tool, some data types need to be converted and scaled as needed. You can handle long and date types here.
only supports the processing of a single Jsonobject object, for complex JSON objects, such as jsonarray arrays, consider traversing first, getting jsonobject before processing.
PackageCommon;ImportJava.lang.reflect.Method; ImportJava.text.SimpleDateFormat; ImportNet.sf.json.JSONObject; /*** Auxiliary processing tool **/ Public classAssistantutil {Private Static FinalSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); /*** Convert JSON data to Java Object * Description: Purpose/function of function*/ Public Static voidSetjsonobjdata (Object obj, jsonobject data, string[] excludes)throwsException {//reflection gets all the methodsMethod[] Methods =Obj.getclass (). Getdeclaredmethods (); if(NULL!=methods) { for(Method m:methods) {String methodName=M.getname (); if(Methodname.startswith ("Set") ) {MethodName= Methodname.substring (3); //Get Property nameMethodName = methodname.substring (0, 1). toLowerCase () + methodname.substring (1); if(!methodname.equalsignorecase ("class") &&!Isexistprop (excludes, methodName)) { Try{m.invoke (obj,Newobject[] {data.get (methodName)}); } Catch(IllegalArgumentException E1) {if(M.getparametertypes () [0].getname (). Equals ("Java.lang.Long") {m.invoke (obj),Newobject[] {long.valueof (Data.get (methodName). toString ())}); }Else if(M.getparametertypes () [0].getname (). Equals ("Java.util.Date") {m.invoke (obj),NewObject[] {data.containskey (methodName)? Sdf.parse (Data.get (methodName). toString ()):NULL}); } } Catch(Exception e) {} } } } } } Private Static BooleanIsexistprop (string[] excludes, String prop) {if(NULL!=excludes) { for(String exclude:excludes) {if(prop.equals (exclude)) {return true; } } } return false; } }
Transform JSON data into Java objects using the Java reflection mechanism