1 PackageUtils;2 3 Importjava.util.ArrayList;4 Importjava.util.List;5 ImportCom.google.gson.Gson;6 ImportCom.google.gson.JsonObject;7 ImportCom.google.gson.reflect.TypeToken;8 ImportJava.lang.reflect.Type;9 ImportBean. User;Ten ImportNet.sf.json.JSONArray; One A Public classGsonutil { - - /** the * Convert JSON data strings to object data - * - * @paramJSON - * @paramCLS + * @return - * @throwsException + */ A Public Static<T> T Fromjson (String json, class<t> CLS)throwsException { atT obj =NULL; -Gson Gson =NewGson (); -obj =cls.newinstance (); -obj =Gson.fromjson (JSON, CLS); - returnobj; - } in - /** to * Convert an object into a JSON data string + * - * @paramobj the * @return * */ $ Public StaticString Objtojson (Object obj) {Panax Notoginseng return NewGson (). ToJson (obj); - } the + /** A * Convert list JSON data string to list collection the * + * @paramJSON - * @paramClas $ * @return $ */ - Public Static<T> arraylist<t> jsontoarraylist (String json, class<t>CLS) { -Type type =NewTypetoken<arraylist<jsonobject>>() { the }.gettype (); -Arraylist<jsonobject> jsonobjects =NewGson (). Fromjson (JSON, type);Wuyi theArraylist<t> ArrayList =NewArraylist<>(); - for(Jsonobject jsonobject:jsonobjects) { WuArraylist.add (NewGson (). Fromjson (Jsonobject, CLS)); - } About returnarrayList; $ } - - /** - * Convert list collection to JSON data string A * + * @paramList the * @return - */ $ Public StaticString Listtojson (Object list) { theJsonarray Jsonarray =jsonarray.fromobject (list); the returnjsonarray.tostring (); the } the - /** in * Test the * Test the * @paramargs About */ the Public Static voidMain (string[] args) { the Try { theUser u1 =NewUser (); +U1.setuid (100000); -U1.setaddress ("SASASSDASD"); theU1.setage (25);BayiU1.setemail ("[Email protected]"); theU1.setname ("Sai"); theString string =Objtojson (U1); -User U2 =NewUser (); -User U3 =NewUser (); theU3.setuid (100000); theU3.setaddress ("SASASSDASD"); theU3.setage (25); theU3.setemail ("[Email protected]"); -U3.setname ("Sai"); theList<user> uList =NewArraylist<user>(); the Ulist.add (U1); the Ulist.add (U3);94String s2 =Listtojson (uList); the theList<user> UList1 =NewArraylist<user>(); theUList1 = jsontoarraylist (S2, User.class);98 About for(User user:ulist1) { - System.out.println (user.tostring ());101 }102 103U2 = Fromjson (String, User.class);104 System.out.println (u2.tostring ()); the}Catch(Exception e) {106 //TODO auto-generated Catch block107 e.printstacktrace ();108 }109 } the 111}
JSON learning: Conversion between JSON data strings, objects, and arrays