Json 自定义使用函数的简单实例
如下所示:
/* *CreatedonNov4,2016 * *TODOTochangethetemplateforthisgeneratedfilegoto *Window-Preferences-Java-CodeStyle-CodeTemplates */ packagecom.suning.commerce.util; importjava.sql.Date; importjava.sql.Time; importjava.sql.Timestamp; importjava.util.Collection; importjava.util.Iterator; importjava.util.Map; importorg.apache.commons.beanutils.BeanUtils; /** *@authornicholastse * *TODOTochangethetemplateforthisgeneratedtypecommentgotoWindow-Preferences-Java-CodeStyle-CodeTemplates */ publicclassJsonUtils{ /** * *@paramarray *@return */ privatestaticStringarray2Json(Object[]array){ if(array.length==0) return"[]"; inti=array.length; StringBuffersb=newStringBuffer(i<<4); sb.append('['); for(intj=0;j<i;j++){ Objecto=array[j]; sb.append(toJson(o)); sb.append(','); } //将最后添加的','变为']': sb.setCharAt(sb.length()-1,']'); returnsb.toString(); } privatestaticStringstring2Json(Strings){ StringBuffersb=newStringBuffer(s.length()+20); sb.append('\"'); for(inti=0;i<s.length();i++){ charc=s.charAt(i); switch(c){ case'\"': sb.append("\\\""); break; case'\\': sb.append("\\\\"); break; case'/': sb.append("\\/"); break; case'\b': sb.append("\\b"); break; case'\f': sb.append("\\f"); break; case'\n': sb.append("\\n"); break; case'\r': sb.append("\\r"); break; case'\t': sb.append("\\t"); break; default: sb.append(c); } } sb.append('\"'); returnsb.toString(); } publicstaticStringtoJson(Objecto){ if(o==null){ return"null"; }elseif(oinstanceofString){ returnstring2Json((String)o); }elseif((oinstanceofBoolean)||(oinstanceofNumber)){ returno.toString(); }elseif((oinstanceofDate)||(oinstanceofTime)||oinstanceofTimestamp){ returno.toString(); }elseif(oinstanceofjava.util.Date){ returnDateUtil.formatDate((java.util.Date)o,"yyyy-MM-ddHH:mm:ss"); }elseif(oinstanceofMap){ returnmap2Json((Map)o); }elseif(oinstanceofObject[]){ returnarray2Json((Object[])o); }elseif(oinstanceofCollection){ returnarray2Json(((Collection)o).toArray()); }else{ try{ Mapdescribe=BeanUtils.describe(o); returnmap2Json(describe); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } thrownewRuntimeException("Unsupportedtype:"+o.getClass().getName()); } /** * *@parammap *@return */ privatestaticStringmap2Json(Mapmap){ if(map.isEmpty()) return"{}"; StringBuffersb=newStringBuffer(map.size()<<4); sb.append('{'); Iteratoriterator=map.keySet().iterator(); while(iterator.hasNext()){ Objectkey=iterator.next(); Objectvalue=map.get(key); sb.append('\"'); sb.append(key); sb.append('\"'); sb.append(':'); sb.append(toJson(value)); sb.append(','); } //将最后的','变为'}': sb.setCharAt(sb.length()-1,'}'); returnsb.toString(); } }
以上就是小编为大家带来的Json自定义使用函数的简单实例全部内容了,希望大家多多支持毛票票~