Jar packages used in this class: participate in the article "using Json-lib to convert between Java and JSON" reprint "
Importjava.util.Collection; ImportJava.util.HashMap; ImportJava.util.Map; ImportNet.sf.json.JSONArray; ImportNet.sf.json.JSONObject; /*** Pojo conversion between JSON and Java * * Jsonhelper.java*/ Public Final classJsonhelper {//convert an array to JSON Public StaticString Array2json (Object object) {Jsonarray Jsonarray=Jsonarray.fromobject (object); returnjsonarray.tostring (); } //converts the JSON into an array, where VALUECLZ is the class of the objects stored in the group Public StaticObject Json2array (String json, Class valueclz) {Jsonarray Jsonarray=Jsonarray.fromobject (JSON); returnJsonarray.toarray (Jsonarray, VALUECLZ); } //Convert collection to JSON Public StaticString Collection2json (Object object) {Jsonarray Jsonarray=Jsonarray.fromobject (object); returnjsonarray.tostring (); } //convert JSON to collection, where Collectionclz is the class of the collection specific subclass,//Valueclz is the class of the objects stored in the collection Public StaticCollection json2collection (String json, Class Collectionclz, class Valueclz) {Jsonarray JSO NArray=Jsonarray.fromobject (JSON); returnjsonarray.tocollection (Jsonarray, VALUECLZ); } //convert map to JSON Public StaticString Map2json (Object object) {Jsonobject Jsonobject=Jsonobject.fromobject (object); returnjsonobject.tostring (); } //convert JSON to map, where Valueclz is the class,keyarray of value in map as the key of map Public StaticMap Json2map (object[] Keyarray, String json, Class valueclz) {jsonobject jsonobject=Jsonobject.fromobject (JSON); Map Classmap=NewHashMap (); for(inti = 0; i < keyarray.length; i++) {classmap.put (keyarray[i], VALUECLZ); } return(MAP) Jsonobject.tobean (Jsonobject, Map.class, Classmap); } //convert Pojo to JSON Public StaticString Bean2json (Object object) {Jsonobject Jsonobject=Jsonobject.fromobject (object); returnjsonobject.tostring (); } //convert JSON to Pojo, where Beanclz is Pojo's class Public StaticObject Json2object (String json, Class beanclz) {returnJsonobject.tobean (Jsonobject.fromobject (JSON), BEANCLZ); } //convert a string into JSON Public Staticstring String2json (String key, String value) {Jsonobject Object=NewJsonobject (); Object.put (key, value); returnobject.tostring (); } //convert JSON to string Public Staticstring json2string (String json, string key) {Jsonobject Jsonobject=Jsonobject.fromobject (JSON); returnJsonobject.get (key). ToString (); } }
JSON and Java Pojo conversion "reprint"