JSON utility class for converting objects and JSON strings to each other
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 Utility class * for converting objects and JSON strings to each other * * @author Aven * @d Ate 2015-01-14 */public class Jsonutil {public static String Object2json (Object obj) {StringBuilder json = new Stringbuild ER (); if (obj = = null) {json.append ("\" \ ");} else if (obj instanceof String | | obj instanceof integer| | obj instanceof Flo at | | obj instanceof boolean| | Obj instanceof Short | | obj instanceof double| | obj instanceof Long | | obj instanceof 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; >) (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 = Objec T2json (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! = Nu ll && 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! = N ull && 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 >= ' \u0000 ' && ch <= ' \u001f ') {String SS = Integer.tohexstri NG (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> T json2object (String jsonstring, class<t> pojocalss) {if (POJOCALSS = null | | jsonstring = = 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". Equalsignorecase (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<string> getList (String propvalue) {list<string> vallist = new arraylist<string> (); 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);}}
JSON utility class for converting objects and JSON strings to each other