Json String Parsing

Source: Internet
Author: User

Json String Parsing

Package com. gamesvr. framework. util; import java. beans. introspectionException; import java. beans. introspector; import java. beans. propertyDescriptor; import java. math. bigDecimal; import java. math. bigInteger; import java. util. *; import java. text. simpleDateFormat; import net. sf. json. JSONArray; import net. sf. json. JSONObject; import net. sf. json. jsonConfig; import net. sf. json. processors. jsonValueProcessor; import net. sf. json. xml. XMLSerializer;/*** @ ClassName: JSONUtil * @ ClassRemark: * @ Author: txxs * @ UpdateRemark: * @ version: */public class JSONUtil {/*** convert objects such as object2JSONString Bean List Map to JsonString *** @ param Object obj (JavaBean List Map Array ...) * @ return JsonString */public static String object2JSONString (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 (string2JSONString (obj. toString ())). append ();} else if (obj instanceof Object []) {json. append (array2JSONString (Object []) obj);} else if (obj instanceof List) {json. append (list2JSONString (List
 ) Obj);} else if (obj instanceof Map) {json. append (map2JSONString (Map
 ) Obj);} else if (obj instanceof Set) {json. append (set2JSONString (Set
 ) Obj);} else {json. append (bean2JSONString (obj);} return json. toString ();}/*** bean2JSONString Bean convert JsonString ** @ param Object bean * @ return JsonString */public static String bean2JSONString (Object bean) {StringBuilder json = new StringBuilder (); json. append ({); PropertyDescriptor [] props = null; try {props = Introspector. getBeanInfo (bean. getClass (), Object. class ). getPropertyDescript Ors ();} catch (IntrospectionException e) {} if (props! = Null) {for (int I = 0; I <props. length; I ++) {try {String name = object2JSONString (props [I]. getName (); String value = object2JSONString (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 ();}/*** list2JSONString List convert JsonString ** @ param List list * @ return JsonString */public static String list2JSONString (List
 List) {StringBuilder json = new StringBuilder (); json. append ([); if (list! = Null & list. size ()> 0) {for (Object obj: list) {json. append (object2JSONString (obj); json. append (,);} json. setCharAt (json. length ()-1, ']');} else {json. append (]);} return json. toString ();}/*** array2JSONString Array convert JsonString ** @ param Object [] array * @ return JsonString */public static String array2JSONString (Object [] array) {StringBuilder json = new StringBuilder (); json. appe Nd ([); if (array! = Null & array. length> 0) {for (Object obj: array) {json. append (object2JSONString (obj); json. append (,);} json. setCharAt (json. length ()-1, ']');} else {json. append (]);} return json. toString ();}/*** map2JSONString Map to convert JsonString ** @ param Map * @ return JsonString */public static String map2JSONString (map
 Map) {StringBuilder json = new StringBuilder (); json. append ({); if (map! = Null & map. size ()> 0) {for (Object key: map. keySet () {json. append (object2JSONString (key); json. append (:); json. append (object2JSONString (map. get (key); json. append (,);} json. setCharAt (json. length ()-1, '}');} else {json. append (});} return json. toString ();}/*** set2JSONString Set to convert JsonString ** @ param Set * @ return JsonString */public static String set2JSONString (set
 Set) {StringBuilder json = new StringBuilder (); json. append ([); if (set! = Null & set. size ()> 0) {for (Object obj: set) {json. append (object2JSONString (obj); json. append (,);} json. setCharAt (json. length ()-1, ']');} else {json. append (]);} return json. toString ();}/*** string2JSONString conversion JsonString ** @ param String s * @ return JsonString * @ Exception (Exception object) */public static String string2JSONString (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 '': sb. append (\ B); break; case '': sb. append (\ f); break; case '': sb. append (\ n); break; case '': sb. append (\ r); break; case '': sb. append (\ t); break; case '/': sb. append (\/); break; default: if (ch> = ''& ch <='') {String ss = Integ Er. 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 ();}/*** convert jsonString2Bean from json string to object *** @ param jsonObjStr e.g. {'name': 'get', 'dateattr': '2017-11-12 '} * @ param clazz Person. class * @ return */public static Object jsonString2Bean (String jsonStr, Class clazz) {return JS ONObject. toBean (JSONObject. fromObject (jsonStr), clazz);}/*** the jsonString2Bean is converted from a json string to an object, and the object set property contains another entity Bean ** @ param jsonStr e.g. {'data': [{'name': 'get'}, {'name': 'set'}]} * @ param clazz e.g. myBean. class * @ param classMap e.g. classMap. put (data, Person. class) * @ return Object */public static Object jsonString2Bean (String jsonStr, Class clazz, Map classMap) {return JSONObject. toBean (JSONOb Ject. fromObject (jsonStr), clazz, classMap);}/*** jsonString2Array converts a json array string to a common array ** @ param jsonArrStr e.g. ['get', 1, true, null] * @ return Object [] */public static Object [] jsonString2Array (String jsonArrStr) {return JSONArray. fromObject (jsonArrStr ). toArray ();}/*** jsonString2List converts a json array string to an object array ** @ param jsonArrStr e.g. [{'name': 'get'}, {'name': 'set'}] * @ param clazz e.g. person. clas S * @ return Object [] */public static Object [] jsonString2List (String jsonArrStr, Class clazz) {JSONArray jsonArr = JSONArray. fromObject (jsonArrStr); Object [] objArr = new Object [jsonArr. size ()]; for (int I = 0; I <jsonArr. size (); I ++) {objArr [I] = JSONObject. toBean (jsonArr. getJSONObject (I), clazz);} return objArr;}/*** jsonString2List converts a json array string to an object array, and the attribute of the array element contains another instance Bean ** @ param jsonArr Str e.g. [{'data': [{'name': 'get'}]}, {'data': [{'name ': 'set'}] * @ param clazz e.g. myBean. class * @ param classMap e.g. classMap. put (data, Person. class) * @ return Object [] */public static Object [] jsonString2List (String jsonArrStr, Class clazz, Map classMap) {JSONArray array = JSONArray. fromObject (jsonArrStr); Object [] obj = new Object [array. size ()]; for (int I = 0; I <array. size (); I ++) {JSONO Bject jsonObject = array. getJSONObject (I); obj [I] = JSONObject. toBean (jsonObject, clazz, classMap);} return obj;}/*** jsonString2List converts a json array string to a set for storing common elements ** @ param jsonArrStr e.g. ['get', 1, true, null] * @ return List */public static List jsonString2List (String jsonArrStr) {JSONArray jsonArr = JSONArray. fromObject (jsonArrStr); List list = new ArrayList (); for (int I = 0; I <jsonArr. size (); I ++) {list. add (jsonArr. get (I);} return list;}/*** jsonString2ListBean converts a json array string into a set and stores the instance Bean in the Set ** @ param jsonArrStr e.g. [{'name': 'get'}, {'name': 'set'}] * @ param clazz * @ return List */public static List jsonString2ListBean (String jsonArrStr, class clazz) {JSONArray jsonArr = JSONArray. fromObject (jsonArrStr); List list = new ArrayList (); for (int I = 0; I <jsonArr. size (); I ++ ){ List. add (JSONObject. toBean (jsonArr. getJSONObject (I), clazz);} return list;}/*** jsonString2ListBean converts a json array string to a set, the object attributes in the Set contain the other instance Bean ** @ param jsonArrStr e.g. [{'data': [{'name': 'get'}]}, {'data': [{'name ': 'set'}] * @ param clazz e.g. myBean. class * @ param classMap e.g. classMap. put (data, Person. class) * @ return List */public static List jsonString2ListBean (String jsonArrStr, Class clazz, Map classMap) {JSONArray jsonArr = JSONArray. fromObject (jsonArrStr); List list = new ArrayList (); for (int I = 0; I <jsonArr. size (); I ++) {list. add (JSONObject. toBean (jsonArr. getJSONObject (I), clazz, classMap);} return list;}/*** jsonString2Map converts a json object string to a map object ** @ param jsonStr e.g. {'name': 'get', 'int': 1, 'double', 1.1, 'null': null} * @ return Map */public static Map jsonString2Map (String JsonStr) {JSONObject jsonObject = JSONObject. fromObject (jsonStr); Map map = new HashMap (); for (Iterator iter = jsonObject. keys (); iter. hasNext ();) {String key = (String) iter. next (); map. put (key, jsonObject. get (key);} return map;}/*** jsonString2MapBean converts a json object string to a map object, and the map object stores other entity beans ** @ param jsonStr e.g. {'data1': {'name': 'get'}, 'data2 ': {'name': 'set'} * @ param clazz e.g. person. c Lass * @ return Map */public static Map jsonString2MapBean (String jsonStr, Class clazz) {JSONObject jsonObject = JSONObject. fromObject (jsonStr); Map map = new HashMap (); for (Iterator iter = jsonObject. keys (); iter. hasNext ();) {String key = (String) iter. next (); map. put (key, JSONObject. toBean (jsonObject. getJSONObject (key), clazz);} return map;}/*** jsonString2MapBean converts a json object string to a map object, and maps Other entity beans in the image also contain other entity beans ** @ param jsonStr e.g. {'mybean': {'data': [{'name': 'get'}]} * @ param clazz e.g. myBean. class * @ param classMap e.g. classMap. put (data, Person. class) * @ return Map */public static Map jsonString2MapBean (String jsonStr, Class clazz, Map classMap) {JSONObject jsonObject = JSONObject. fromObject (jsonStr); Map map = new HashMap (); for (Iterator iter = jsonObject. keys (); iter. HasNext ();) {String key = (String) iter. next (); map. put (key, JSONObject. toBean (jsonObject. getJSONObject (key), clazz, classMap);} return map ;} /*** object2JsonString converts object beans, Map objects, arrays, and list sets into Json strings ** @ param obj * @ return * @ throws Exception String */public static String object2JsonString (object obj) {String jsonStr = null; // Json configuration JsonConfig jsonCfg = new JsonConfig (); // register the Date Processor jsonCfg. re GisterJsonValueProcessor (java. util. date. class, new JsonDateValueProcessor (yyyyMMdd_HHmmss); if (obj = null) {return {};} if (obj instanceof Collection | obj instanceof Object []) {jsonStr = JSONArray. fromObject (obj, jsonCfg ). toString ();} else {jsonStr = JSONObject. fromObject (obj, jsonCfg ). toString ();} return jsonStr;}/*** object2XML converts json strings, arrays, collections (collection map), and object beans into XML * XMLSeriali Zer API: * http://json-lib.sourceforge.net/apidocs/net/sf/json/xml/XMLSerializer.html * specific instance please refer to: * http://json-lib.sourceforge.net/xref-test/net/sf/json/xml/TestXMLSerializer_writes.html ** @ param obj * @ return * @ throws Exception String */public static String object2XML (Object obj) {XMLSerializer xmlSeria L = new XMLSerializer (); // Json configuration JsonConfig jsonCfg = new JsonConfig (); // register Date Processor jsonCfg. registerJsonValueProcessor (java. util. date. class, new JsonDateValueProcessor (yyyyMMdd_HHmmss); if (String. class. isInstance (obj) & String. valueOf (obj ). startsWith ([) | obj. getClass (). isArray () | Collection. class. isInstance (obj) {JSONArray jsonArr = JSONArray. fromObject (obj, jsonCfg); return xmlSerial. wr Ite (jsonArr);} else {JSONObject jsonObj = JSONObject. fromObject (obj, jsonCfg); return xmlSerial. write (jsonObj) ;}}/*** convert xml2JsonString from XML to json String ** @ param xml * @ return String */public static String xml2JsonString (String xml) {XMLSerializer xmlSerial = new XMLSerializer (); return String. valueOf (xmlSerial. read (xml) ;}}/*** @ ProjectName: srp * @ ClassName: JsonDateValueProcessor Json Date Processor *@ ClassRemark: * @ Author: T08388 * @ UpdateRemark: * @ version: 1 */class JsonDateValueProcessor implements JsonValueProcessor {private String format = signature; public JsonDateValueProcessor () {} public JsonDateValueProcessor (String format) {this. format = format;} public Object processArrayValue (Object value, JsonConfig jsonConfig) {return process (value, jsonConfig);} public Object proces SObjectValue (String key, Object value, JsonConfig jsonConfig) {return process (value, jsonConfig);} private Object process (Object value, JsonConfig jsonConfig) {if (value instanceof Date) {String str = new SimpleDateFormat (format ). format (Date) value); return str;} return value = null? Null: value. toString ();} public String getFormat () {return format;} public void setFormat (String format) {this. format = format ;}}
 

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.