1 PackageCom.liveyc.restfull.until;2 3 ImportJava.util.HashMap;4 ImportJava.util.Iterator;5 Importjava.util.List;6 7 ImportOrg.apache.commons.logging.Log;8 Importorg.apache.commons.logging.LogFactory;9 ImportOrg.codehaus.jackson.map.ObjectMapper;Ten ImportOrg.codehaus.jackson.type.JavaType; One A ImportNet.sf.json.JSONArray; - ImportNet.sf.json.JSONObject; - the Public classJsontools { - - Public StaticLog log = Logfactory.getlog (jsontools.class); - + Private StaticObjectmapper Objectmapper =NewObjectmapper (); - /** + * A * @authorJSON Tool class at * @param - * - */ - - - /*** in * Serializes objects into JSON text - * @paramObject to * @return + */ - Public StaticString tojsonstring (Object object) the { *Jsonarray Jsonarray =Jsonarray.fromobject (object); $ Panax Notoginseng returnjsonarray.tostring (); - } the + /*** A * Serializes JSON objects into JSON text the * @paramJsonobject + * @return - */ $ Public StaticString toobjstring (Object object) $ { -Jsonobject Jsonobject =Jsonobject.fromobject (object); - returnjsonobject.tostring (); the } - Wuyi /*** the * Convert an object to an array of JSON objects - * @paramObject Wu * @return - */ About Public StaticJsonarray Tojsonarray (Object object) $ { - returnJsonarray.fromobject (object); - } - A /*** + * Convert an object to a JSON object the * @paramObject - * @return $ */ the Public Staticjsonobject Tojsonobject (Object object) the { the returnJsonobject.fromobject (object); the } - in /*** the * Convert an object to HashMap the * @paramObject About * @return the */ the Public StaticHashMap Tohashmap (Object object) the { +hashmap<string, object> data =NewHashmap<string, object>(); -Jsonobject Jsonobject =Jsontools.tojsonobject (object); theIterator it =Jsonobject.keys ();Bayi while(It.hasnext ()) the { theString key =string.valueof (It.next ()); -Object value =Jsonobject.get (key); - data.put (key, value); the } the the returndata; the } - the the the 94 the the Public Static<T> T Json2bean (String json, class<t>Beanclass) { the Try { 98 returnObjectmapper.readvalue (JSON, beanclass); About}Catch(Exception e) { - Log.error (e);101 NewException ("Error parsing parameter");102 } 103 return NULL; 104 } the 106 107 Public Static<T> list<t> json2list (String json, class<t>Beanclass) { 108 Try { 109 return(list<t>) Objectmapper.readvalue (JSON, Getcollectiontype (List.class, Beanclass)); the}Catch(Exception e) {111 E.printstacktrace (); the } 113 return NULL; the } the the Public StaticString getjsonfromobject (Object obj) {117 Try {118 returnobjectmapper.writevalueasstring (obj);119}Catch(Exception e) { - e.printstacktrace ();121 }122 return NULL;123 }124 the Public StaticJavatype Getcollectiontype (class<?> collectionclass, class<?>... elementclasses) { 126 returnobjectmapper.gettypefactory (). Constructparametrictype (Collectionclass, elementclasses); 127 } -}
Some common ways to do this in JSON format