JSON character class, used to convert objects and JSON strings

Source: Internet
Author: User

JSON character class, used to convert objects and JSON strings

JSON character class, used to convert objects and JSON strings

Import java. beans. introspectionException; import java. beans. introspector; import java. beans. propertyDescriptor; import java. lang. reflect. field; import java. math. bigDecimal; import java. math. bigInteger; import java. util. arrayList; import java. util. list; import java. util. map; import java. util. set; /*** JSON character class * is used to convert objects and JSON strings ** @ author aven * @ date 2015-01-14 */public class JSONUtil {public static String object2json (Object obj) {StringBuilder json = new StringBuilder (); if (obj = null) {json. append ("\"\"");} else if (obj instanceof String | obj instanceof Integer | obj instanceof Float | obj instanceof Boolean | obj instanceof Short | obj instanceof Double | obj instanceof Long | obj instanceof Integer bigDecimal | obj instanceof BigInteger | obj instanceof Byte) {json. append ("\""). append (string2json (obj. toString ())). append ("\" ");} else if (obj instanceof Object []) {json. append (array2json (Object []) obj);} else if (obj instanceof List) {json. append (list2json (List
 ) Obj);} else if (obj instanceof Map) {json. append (map2json (Map
 ) Obj);} else if (obj instanceof Set) {json. append (set2json (Set
 ) Obj);} else {json. append (bean2json (obj);} return json. toString ();} public static String bean2json (Object bean) {StringBuilder json = new StringBuilder (); json. append ("{"); PropertyDescriptor [] props = null; try {props = Introspector. getBeanInfo (bean. getClass (), Object. class ). getPropertyDescriptors ();} catch (IntrospectionException e) {} if (props! = Null) {for (int I = 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 ("}");} return json. toString ();} public static String list2json (List
 List) {StringBuilder json = new StringBuilder (); 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 ("]");} return json. toString ();} public static String array2json (Object [] array) {StringBuilder json = new StringBuilder (); 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 ("]");} return json. toString ();} public static String map2json (Map
 Map) {StringBuilder json = new StringBuilder (); 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 ("}");} return json. toString ();} public static String set2json (Set
 Set) {StringBuilder json = new StringBuilder (); 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 ("]");} return json. toString ();} public static String string2json (String s) {if (s = null) return ""; StringBuilder sb = new StringBuilder (); for (int I = 0; I <s. length (); I ++) {char ch = 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> = '\ u000000' & ch <=' \ u001f') {String ss = Integer. toHexString (ch); sb. append ("\ u"); for (int k = 0; k <4-ss. length (); k ++) {sb. append ('0');} sb. append (ss. toUpperCase ();} else {sb. append (ch) ;}} return sb. toString ();} public static
 
  
T json2Object (String jsonString, Class
  
   
PojoCalss) {if (pojoCalss = null | jsonString. trim (). isEmpty () {return null;} try {T pojo = (T) pojoCalss. newInstance (); Field [] fields = pojo. getClass (). getDeclaredFields (); String simpleName = ""; for (Field f: fields) {try {if (f. getName () = null) {continue;} if (f. getModifiers ()> 2) {continue;} f. setAccessible (true); simpleName = f. getType (). getSimpleName (); String propName =" \ "" + F. getName () + "\": "; Integer idx = jsonString. indexOf (propName); if (idx =-1) {continue;} Integer idxStart = idx + propName. length (); if (jsonString. length () <idxStart) {continue;} String valStart = jsonString. substring (idxStart, idxStart + 1); if (valStart. equals ("[") {valStart = "]";} else if (valStart. equals ("{") {valStart = "}" ;}else {if (! ValStart. equals ("\" ") {valStart =", ";}} String propValue = null; Integer idxEnd =-1; if (valStart. equals (",") {idxEnd = jsonString. indexOf (valStart, idxStart); if (idxEnd =-1) {continue;} propValue = jsonString. substring (idxStart, idxEnd);} else {idxEnd = jsonString. indexOf (valStart, idxStart + 1); if (idxEnd =-1) {continue;} propValue = jsonString. substring (idxStart + 1, idxEnd);} if (propValue = null) {continue;} if (simpleName. equals ("String") | simpleName. equals ("Object") {f. set (pojo, propValue); continue;} if (simpleName. equals ("Long") | simpleName. equals ("long") {f. set (pojo, getLong (propValue); continue;} if (simpleName. equals ("Integer") | simpleName. equals ("int") {f. set (pojo, getInteger (propValue); continue;} if (simpleName. equals ("Boolean") {f. set (pojo, getBoolean (propValue); continue;} if (simpleName. equals ("Double") {f. set (pojo, getDouble (propValue); continue;} if (simpleName. equals ("Float") {f. set (pojo, getFloat (propValue); continue;} if (simpleName. equals ("Byte") {f. set (pojo, getByte (propValue); continue;} if (simpleName. equals ("List") {f. set (pojo, getList (propValue); continue ;}} catch (Exception ex) {ex. printStackTrace () ;}} return pojo;} catch (Exception e) {e. printStackTrace (); return null ;}} public static Long getLong (String propValue) {Long val = 0L; try {val = Long. parseLong (propValue);} catch (Exception el) {} return val;} public static Integer getInteger (String propValue) {Integer val = 0; try {val = Integer. parseInt (propValue);} catch (Exception el) {} return val;} public static Boolean getBoolean (String propValue) {Boolean val = ("1 ". equals (propValue) | "true ". inclusignorecase (propValue); return val;} public static Double getDouble (String propValue) {Double val = 0D; try {val = Double. parseDouble (propValue);} catch (Exception el) {} return val;} public static Float getFloat (String propValue) {Float val = 0F; try {val = Float. parseFloat (propValue);} catch (Exception el) {} return val;} public static Byte getByte (String propValue) {Byte val = 0; try {val = Byte. parseByte (propValue);} catch (Exception el) {} return val;} public static List
   
    
GetList (String propValue) {List
    
     
ValList = new ArrayList
     
      
(); If (propValue! = Null &&! PropValue. trim (). isEmpty () {try {String [] aptEvents = propValue. replace ("\"",""). toLowerCase (). split (","); valList = java. util. arrays. asList (aptEvents);} catch (Exception ex) {ex. printStackTrace () ;}} return valList;} public static void main (String [] args) {String json = JSONUtil. object2json (new Data (); System. out. println (json );}}
     
    
   
  
 


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.