Java converts other data formats into JSON string formats

Source: Internet
Author: User
Tags set set string format

 PackageCom.wangbo.util;Importjava.beans.IntrospectionException;ImportJava.beans.Introspector;ImportJava.beans.PropertyDescriptor;ImportJava.math.BigDecimal;ImportJava.math.BigInteger;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;ImportJava.util.Set;/*** Convert other data formats to JSON string format*/ Public classJsonutil {/** object is converted to JSON string*/@SuppressWarnings ("Unchecked")     Public StaticString Object2json (Object obj) {StringBuilder json=NewStringBuilder (); if(obj = =NULL) {json.append ("\"\""); } Else if(objinstanceofString | | ObjinstanceofInteger | | ObjinstanceofFloat|| ObjinstanceofBoolean | | ObjinstanceofShort | | ObjinstanceofDouble|| ObjinstanceofLong | | ObjinstanceofBigDecimal | | ObjinstanceofBigInteger|| ObjinstanceofByte) {Json.append ("\" "). Append (String2json (obj.tostring ())). Append (" \ ""); } Else if(objinstanceofobject[])          {Json.append (Array2json ((object[)) obj); } Else if(objinstanceofList) {Json.append (List2json (List<?>) (obj)); } Else if(objinstanceofMap) {Json.append (Map2json (Map<?,? >) (obj)); } Else if(objinstanceofSet) {Json.append (Set2json (Set<?>) (obj)); } Else{json.append (Bean2json (obj)); }          returnjson.tostring (); }    /** Bean converted to JSON string*/     Public StaticString Bean2json (Object Bean) {StringBuilder json=NewStringBuilder (); Json.append ("{"); propertydescriptor[] Props=NULL; Try{Props= Introspector.getbeaninfo (Bean.getclass (), Object.class). Getpropertydescriptors (); } Catch(Introspectionexception e) {}if(Props! =NULL) {               for(inti = 0; i < props.length; i++) {                  Try{String name=Object2json (Props[i].getname ()); String value=Object2json (Props[i].getreadmethod (). Invoke (bean));                      Json.append (name); Json.append (":");                      Json.append (value); Json.append (","); } Catch(Exception e) {}} Json.setcharat (Json.length ()-1, '} '); } Else{json.append ("}"); }           returnjson.tostring (); }    /** List collection converted to JSON string*/     Public StaticString List2json (list<?>list) {StringBuilder JSON=NewStringBuilder (); Json.append ("["); if(List! =NULL&& list.size () > 0) {               for(Object obj:list) {json.append (Object2json (obj)); Json.append (","); } Json.setcharat (Json.length ()-1, '] '); } Else{json.append ("]"); }          returnjson.tostring (); }    /** Array to JSON string*/     Public StaticString Array2json (object[] array) {StringBuilder json=NewStringBuilder (); Json.append ("["); if(Array! =NULL&& array.length > 0) {               for(Object obj:array) {json.append (Object2json (obj)); Json.append (","); } Json.setcharat (Json.length ()-1, '] '); } Else{json.append ("]"); }          returnjson.tostring (); }    /** Map collection to JSON string*/     Public StaticString Map2json (map<?,? >map) {StringBuilder JSON=NewStringBuilder (); Json.append ("{"); if(Map! =NULL&& map.size () > 0) {               for(Object key:map.keySet ()) {Json.append (Object2json (key)); Json.append (":");                  Json.append (Object2json (Map.get (key)); Json.append (","); } Json.setcharat (Json.length ()-1, '} '); } Else{json.append ("}"); }          returnjson.tostring (); }    /** Set set to JSON string*/     Public StaticString Set2json (set<?>set) {StringBuilder JSON=NewStringBuilder (); Json.append ("["); if(Set! =NULL&& set.size () > 0) {               for(Object obj:set) {json.append (Object2json (obj)); Json.append (","); } Json.setcharat (Json.length ()-1, '] '); } Else{json.append ("]"); }          returnjson.tostring (); }    /** String converted to JSON string*/     Public Staticstring String2json (string s) {if(s = =NULL)              return""; StringBuilder SB=NewStringBuilder ();  for(inti = 0; I < s.length (); i++) {              CharCH =S.charat (i); Switch(CH) { 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;  Case‘/‘: Sb.append ("\\/");  Break; default:                     if(Ch >= ' \u0000 ' && ch <= ' \u001f ') {String ss=integer.tohexstring (CH); Sb.append ("\\u");  for(intk = 0; K < 4-ss.length (); k++) {sb.append (' 0 ');                     } sb.append (Ss.touppercase ()); } Else{sb.append (ch); }            }        }        returnsb.tostring (); }        /** Test Main method*/     Public Static voidMain (string[] args) {Map<string, string> map =NewHashmap<string, string>(); Map.put ("AA", "SSS"); Map.put ("BB", "SSD"); Map.put ("CC", "SUA");    SYSTEM.OUT.PRINTLN (Object2json (map)); }}  

Java converts other data formats into JSON string formats

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.