1 Packagecom;2 3 Importjava.util.ArrayList;4 ImportJava.util.HashMap;5 Importjava.util.List;6 ImportJava.util.Map;7 ImportJava.util.Set;8 9 Importorg.junit.Test;Ten One Public classTestjson { A - Staticstring String2json (string s) { -StringBuilder SB =NewStringBuilder (s.length () + 20); theSb.append (' \ ' ')); - for(inti = 0; I < s.length (); i++) { - Charc =S.charat (i); - Switch(c) { + Case‘\"‘: -Sb.append ("\\\" "); + Break; A Case‘\\‘: atSb.append ("\\\\"); - Break; - Case‘/‘: -Sb.append ("\\/"); - Break; - Case' \b ': inSb.append ("\\b"); - Break; to Case' \f ': +Sb.append ("\\f"); - Break; the Case' \ n ': *Sb.append ("\\n"); $ Break;Panax Notoginseng Case' \ r ': -Sb.append ("\\r"); the Break; + Case' \ t ': ASb.append ("\\t"); the Break; + default: - Sb.append (c); $ } $ } -Sb.append (' \ ' ')); - returnsb.tostring (); the } - Wuyi StaticString Number2json (number number) { the returnnumber.tostring (); - } Wu - StaticString Boolean2json (Boolean bool) { About returnbool.tostring (); $ } - - StaticString Array2json (object[] array) { - if(Array.Length = = 0) A return"[]"; +StringBuilder SB =NewStringBuilder (Array.Length << 4); theSb.append (' ['); - for(Object o:array) { $ sb.append (ToJson (o)); theSb.append (', '); the } the //The last added ', ' becomes '] ': theSb.setcharat (Sb.length ()-1, '] '); - returnsb.tostring (); in } the the StaticString Map2json (map<string, object>map) { About if(Map.isempty ()) the return"{}"; theStringBuilder SB =NewStringBuilder (Map.size () << 4); theSb.append (' {')); +set<string> keys =Map.keyset (); - for(String key:keys) { theObject value =Map.get (key);BayiSb.append (' \ ' ')); the sb.append (key); theSb.append (' \ ' ')); -Sb.append (': ')); - sb.append (ToJson (value)); theSb.append (', '); the } the //Change the last ', ' to '} ': theSb.setcharat (Sb.length ()-1, '} '); - returnsb.tostring (); the } the the Public StaticString ToJson (Object o) {94 if(O = =NULL) the return"NULL"; the if(OinstanceofString) the returnString2json (String) o);98 if(OinstanceofBoolean) About returnBoolean2json ((Boolean) o); - if(OinstanceofNumber )101 returnNumber2json (number) o);102 if(OinstanceofMap)103 returnMap2json (map<string, object>) o);104 if(Oinstanceofobject[]) the returnArray2json ((object[]) o);106 Throw NewRuntimeException ("Unsupported type:"107+O.getclass (). GetName ());108 }109 the@Test (expected = Stackoverflowerror.class)111 Public voidTestrecurrsivemap2json () { themap<string, object> map =NewHashmap<string, object>();113Map.put ("Key", "value"); theMap.put ("Key2", 2); thelist<integer> array =NewArraylist<integer>(); theArray.add (1); 117Array.add (2);118Map.put ("Array", array);119String JSON =Testjson.tojson (map); - System.out.println (JSON);121 }122}
Reference documents:
http://www.ibm.com/developerworks/cn/web/wa-lo-json/
Http://www.w3school.com.cn/json/index.asp
Java Object goto JSON format