1. Add a Dependency package
<Dependency> <groupId>Com.alibaba</groupId> <Artifactid>Fastjson</Artifactid> <version>1.1.41</version></Dependency>
2. Code
PackageCom.yys.common.util;ImportCom.alibaba.fastjson.JSON;ImportCom.alibaba.fastjson.JSONArray;ImportCom.alibaba.fastjson.JSONObject;Importcom.alibaba.fastjson.TypeReference;ImportCom.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;ImportCom.alibaba.fastjson.serializer.SerializeConfig;Importcom.alibaba.fastjson.serializer.SerializerFeature;ImportCom.sun.tools.doclets.formats.html.SourceToHTMLConverter;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;/*** User: Yang Yongsheng * date:9:24 2017/9/6 * Email: [Email protected]*/ Public classFastjsonutils {Private Final StaticLogger Logger = Loggerfactory.getlogger (fastjsonutils.class); Private Staticserializeconfig config; Static{config=NewSerializeconfig (); Config.put (java.util.Date.class,NewJsonlibdataformatserializer ());//use and Json-lib compatible date output formatsConfig.put (java.sql.Date.class,NewJsonlibdataformatserializer ());//use and Json-lib compatible date output formats } Private Static FinalSerializerfeature[] Features ={serializerfeature.disablecircularreferencedetect,//turn on circular reference detection, Jsonfield (serialize = false) does not loopSerializerfeature.writedateusedateformat,//default format date using system default formattingSerializerfeature.writemapnullvalue,//Output empty fieldsSerializerfeature.writenulllistasempty,//If the list field is NULL, the output is [] instead of NULLSerializerfeature.writenullnumberaszero,//numeric field if NULL, the output is 0 instead of NULLSerializerfeature.writenullbooleanasfalse,//If the Boolean field is NULL, the output is false instead of NULLSerializerfeature.writenullstringasempty//character Type field if NULL, the output is "" instead of NULL }; /*** Returns an object contained within the JSON string * *@paramjsonstr: {' City ': ' China ', ' map1 ': [{' Age ': ' + ', ' name ': ' Yys '}]} *@paramList_str:map1 *@paramClazz:Map.class, or other objects *@param<T>: Map *@return:list<map>*/ Public Static Final<T> list<t>json2childlist (String jsonstr, String list_str, Class<T>clazz) {Jsonobject Jsonobj=Json.parseobject (JSONSTR); if(Jsonobj = =NULL) { return NULL; } Object obj=Jsonobj.get (LIST_STR); if(obj = =NULL) { return NULL; } if(objinstanceofJsonarray) {Jsonarray Jsonarr=(jsonarray) obj; List<T> list =NewArraylist<t>(); for(inti = 0; I < jsonarr.size (); i++) {List.add (Jsonarr.getobject (i, clazz)); } returnlist; } return NULL; } /*** Returns an object contained within the JSON string * *@paramjsonstr: {"department": {"id": "1", "Name": "Production department"}, "password": "admin", "username": "admin"} *@paramobj_str:d epartment *@paramClazz:Map.class, or other objects *@param<T>: Map *@return */ Public Static Final<T>T json2childobj (String jsonstr, String obj_str, Class<T>clazz) {Jsonobject Jsonobj=Json.parseobject (JSONSTR); if(Jsonobj = =NULL) { return NULL; } Object obj=Jsonobj.get (OBJ_STR); if(obj = =NULL) { return NULL; } if(objinstanceofjsonobject) { returnJsonobj.getobject (Obj_str, clazz); } Else{logger.info (Obj.getclass ()+ ""); } return NULL; } /*** JSON converted to Object * *@paramJsonstr *@paramClazz *@param<T> *@return */ Public Static Final<T> T json2obj (String jsonstr, class<t>clazz) {T T=NULL; Try{T=Json.parseobject (Jsonstr, clazz); } Catch(Exception e) {logger.error ("JSON string conversion failed!" " +Jsonstr, E); } returnT; } /*** Object converted to JSON string (with formatted output) * *@paramobject to convert *@paramPrettyformat whether to format the JSON string and output a string with wrap and indent *@returnreturns a JSON string array*/ Public Static FinalString Obj2json (Object object,BooleanPrettyformat) { returnjson.tojsonstring (object, Prettyformat); } /*** Object converted to JSON String * *@paramobject to convert *@returnreturns a JSON string array*/ Public Static FinalString Obj2jsonbyfeatures (Object object) {returnjson.tojsonstring (object,config,features); } /*** Object converted to JSON String * *@paramobject to convert *@returnreturns a JSON string array*/ Public Static FinalString Obj2json (Object object) {returnjson.tojsonstring (object,config); } /*** JSON string converted to original Object Object * *@paramJsonstr *@return */ Public Static FinalObject json2obj (String jsonstr) {returnJson.parse (JSONSTR); } /*** JSON string converted to list * *@paramjsonstr JSON String *@paramclazz the class to be converted *@param<T> returned generic type *@returnreturned <T> generic types*/ Public Static<T> list<t> json2list (String jsonstr, class<t>clazz) {List<T> list =NewArraylist<t>(); Try{List=Json.parsearray (Jsonstr, clazz); } Catch(Exception e) {logger.error ("JSON string goto list failed!" " +Jsonstr, E); } returnlist; } /*** JSON string converted to map * *@paramjsonstr JSON String *@returnMap*/ Public StaticMap<string, object>Json2map (String jsonstr) {Try { returnJson.parseobject (Jsonstr, Map.class); } Catch(Exception e) {logger.error ("JSON string conversion failed!" " +Jsonstr, E); } return NULL; } /*** JSON converted to list<map> * *@paramjsonstring *@return */ Public StaticList<map<string, object>>Json2listkeymap (String jsonstring) {List<map<string, object>> list =NewArraylist<map<string, object>>(); Try{List=Json.parseobject (jsonstring,NewTypereference<list<map<string, object>>>() { }); } Catch(Exception e) {logger.error ("JSON string goto map Failed", E); } returnlist; }}
Encapsulation of the JSON Parsing tool (Fastjson-->java)