When you need to use the data of the JSON object, you often write a lot of code, and there are many copy and paste. In order to use POJO's thoughts, we can install JSON to transform into a physical object for operation.
package myth; Import java.io.ioException; Import myproject.Student; Import MyProject.StudentList; Import Pper; Import org.json.jsonarray; Import org.json.jsonexception; Import org.json. JsonObject;/** * * physical class and JSON objects transform each other (jackson-all-1.7.6.jar, JSOUP -.5.2.jar) * @Authouse * * */Public class jsonutil {/** * Convert json into entity POJO * @Param jsonstr * @param obj * @Return */ Public Static <T> Object jsontoobj (string jsonstr, class <t> obj) {t T = null; ctmapper objectMapper = New ObjectMapper (); T = ObjectMapper.Readvalue (JSONSTR, OBJ);} Catch (Exception E) {e.printstacktrace ();} Return T;} /** * transforms the entity pojo to json * @para obj * @Return * @throws jsonexception * @Throws IOEXCEPTION */ Public Static <T> JSONObject Objecttojson (TOLJ) Throws JSONEXCEPTION, IOEXCEPTION {ObjectMapper M Apper = new objectMapper (); // Convert object to json string string jsonstr = "" "; try {jsonstr = Mapper.Writevalueasstring (obj);} Catch (IOEXception E) {Throw E;} Return New JSONObject (JSONSTR);} Public Static Void Main (String [] ARGS) Thro ws jsonexception, ioException {jsonObject obj = null; obj = new jsonObject (); Obj.put ("name", "213"); obj.put ("Age", 27); jsonarray array = new jsonarray (); array.put (obj); obj = new jsonObject (); obj .put ("name", "214"); obj.put ("Age", 28); array.put (obj); Student Stu = (Student) jsontoobj (obj.tostration (), student.class); jsonObject objlist = new jsonObject (); Objlist.put ("Student", Array); System.out.println ("Objlist:"+Objlist); StudentList Stulist = (StudentList) j (Objlist.tostring (), StudentList.class) ; System.out.println("student:"+stu); System.out.println("stuList:"+stuList); System.out.println("############## ######################## This);
The above is all the contents of this article. I hope everyone can like it.