JAVA && JSON

Source: Internet
Author: User


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 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) {
Logger.error ("Exception raised-------->", 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 >= ' \u0000 ' && 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 ();
}

/***************************************************************************
* Serializes objects into JSON text
*
* @param Object
* @return
*/
public static String toJSONString (Object object) {
Jsonarray Jsonarray = Jsonarray.fromobject (object);

return jsonarray.tostring ();
}

/***************************************************************************
* Serializes a JSON object array into JSON text
*
* @param Jsonarray
* @return
*/
public static String tojsonstring (Jsonarray jsonarray) {
return jsonarray.tostring ();
}

/***************************************************************************
* Serializes JSON objects into JSON text
*
* @param jsonobject
* @return
*/
public static String tojsonstring (Jsonobject jsonobject) {
return jsonobject.tostring ();
}

/***************************************************************************
* Convert an object to a list object
*
* @param Object
* @return
*/
public static List Toarraylist (Object object) {
List arrayList = new ArrayList ();

Jsonarray Jsonarray = Jsonarray.fromobject (object);
Iterator it = Jsonarray.iterator ();
while (It.hasnext ()) {
Jsonobject Jsonobject = (jsonobject) it.next ();

Iterator keys = Jsonobject.keys ();
while (Keys.hasnext ()) {
Object key = Keys.next ();
Object value = Jsonobject.get (key);
Arraylist.add (value);
}
}

return arrayList;
}

/***************************************************************************
* Convert an object to an array of JSON objects
*
* @param Object
* @return
*/
public static Jsonarray Tojsonarray (Object object) {
return Jsonarray.fromobject (object);
}

/***************************************************************************
* Convert an object to a JSON object
*
* @param Object
* @return
*/
public static Jsonobject Tojsonobject (Object object) {
return Jsonobject.fromobject (object);
}

/***************************************************************************
* Convert an object to HashMap
*
* @param Object
* @return
*/
public static HashMap Tohashmap (Object object) {
hashmap<string, object> data = new hashmap<string, object> ();
Jsonobject Jsonobject = Tojsonobject (object);
Iterator it = Jsonobject.keys ();
while (It.hasnext ()) {
String key = String.valueof (It.next ());
Object value = Jsonobject.get (key);
Data.put (key, value);
}

return data;
}

public static TreeMap Totreemap (Object object) {
treemap<string, object> data = new treemap<string, object> ();
Jsonobject Jsonobject = Tojsonobject (object);
Iterator it = Jsonobject.keys ();
while (It.hasnext ()) {
String key = String.valueof (It.next ());
Object value = Jsonobject.get (key);
Data.put (key, value);
}
return data;
}

public static Linkedhashmap Tolinkedhashmap (Object object) {
linkedhashmap<string, object> data = new linkedhashmap<string, object> ();
Jsonobject Jsonobject = Tojsonobject (object);
Iterator it = Jsonobject.keys ();
while (It.hasnext ()) {
String key = String.valueof (It.next ());
Object value = Jsonobject.get (key);
Data.put (key, value);
}
return data;
}
/***************************************************************************
* Convert an object to list<map<string,object>>
*
* @param Object
* @return
*/
Returns a list of non-entity types (map<string,object>)
public static list<map<string, object>> toList (Object object) {
list<map<string, object>> list = new arraylist<map<string, object>> ();
Jsonarray Jsonarray = Jsonarray.fromobject (object);
for (Object Obj:jsonarray) {
Jsonobject Jsonobject = (jsonobject) obj;
map<string, object> map = new hashmap<string, object> ();
Iterator it = Jsonobject.keys ();
while (It.hasnext ()) {
String key = (string) it.next ();
Object value = Jsonobject.get (key);
Map.put (String) key, value);
}
List.add (map);
}
return list;
}

/***************************************************************************
* Converts an array of JSON objects into a list of incoming types
*
* @param <T>
* @param Jsonarray
* @param objectClass
* @return
*/
public static <T> list<t> toList (Jsonarray jsonarray, class<t> objectClass) {
Return Jsonarray.tolist (Jsonarray, ObjectClass);
}

/***************************************************************************
* Convert an object to a list of incoming types
*
* @param <T>
* @param
* @param objectClass
* @return
*/
public static <T> list<t> toList (Object object, Class<t> objectClass) {
Jsonarray Jsonarray = Jsonarray.fromobject (object);

Return Jsonarray.tolist (Jsonarray, ObjectClass);
}

/***************************************************************************
* Convert a JSON object to an object of an incoming type
*
* @param <T>
* @param jsonobject
* @param beanclass
* @return
*/
public static <T> T Tobean (jsonobject jsonobject, class<t> beanclass) {
Return (T) Jsonobject.tobean (Jsonobject, Beanclass);
}

/***************************************************************************
* Converts an object to an object of an incoming type
*
* @param <T>
* @param Object
* @param beanclass
* @return
*/
public static <T> T Tobean (Object object, Class<t> beanclass) {
Jsonobject Jsonobject = Jsonobject.fromobject (object);

Return (T) Jsonobject.tobean (Jsonobject, Beanclass);
}

/***************************************************************************
* Deserialize JSON text as the entity from the relationship
*
* @param <T>
* Generic T represents the primary entity type
* @param <D>
* Generic D stands for from entity type
* @param jsonstring
* JSON text
* @param mainClass
* Primary entity type
* @param detailname
* Attribute names from entity classes in the primary entity class
* @param detailclass
* FROM entity type
* @return
*/
public static <t, d> T Tobean (String jsonstring, class<t> MainClass,
String Detailname, class<d> detailclass) {
Jsonobject jsonobject = Jsonobject.fromobject (jsonstring);
Jsonarray Jsonarray = (jsonarray) jsonobject.get (detailname);

T mainentity = Tobean (Jsonobject, MainClass);
list<d> detaillist = toList (Jsonarray, Detailclass);

try {
Beanutils.setproperty (mainentity, Detailname, detaillist);
} catch (Exception ex) {
throw new RuntimeException ("Master-Detail JSON deserialization entity failed!") ");
}

return mainentity;
}

/***************************************************************************
* Deserializes JSON text into the entity from the relationship
*
* @param <T> Generic T
* represents the primary entity type
* @param <D1> Generic D1
* represents from entity type
* @param <D2> generics D2
* represents from entity type * @param jsonstring
* JSON text
* @param mainClass
* Primary entity type
* @param detailName1
* Properties from entity class in primary entity class
* @param detailClass1
* from entity type
* @param detailName2
* Properties from entity class in primary entity class
* @param detailClass2
* from entity type
* @ Return
*/
public static <t, D1, d2> T tobean (String jsonstring, class<t> mainClass,
string Detailna ME1, class<d1> DetailClass1, String detailName2,
class<d2> detailClass2) {
Jsonobject jsonobject = Jsonobject.fromobject (jsonstring);
Jsonarray jsonArray1 = (jsonarray) jsonobject.get (detailName1);
Jsonarray jsonArray2 = (jsonarray) jsonobject.get (detailName2);

T mainentity = Tobean (Jsonobject, MainClass);
list<d1> detailList1 = toList (JsonArray1, DETAILCLASS1);
list<d2> detailList2 = toList (JsonArray2, DETAILCLASS2);

try {
Beanutils.setproperty (mainentity, detailName1, DetailList1);
Beanutils.setproperty (mainentity, detailName2, DetailList2);
} catch (Exception ex) {
throw new RuntimeException ("Master-Detail JSON deserialization entity failed!") ");
}

return mainentity;
}

/***************************************************************************
* Deserialize JSON text as the entity from the relationship
*
* @param <T> generics T
* Represents the primary entity type
* @param <D1> generics D1
* Represents from entity type
* @param <D2> generics D2
* Represents from entity type
* @param jsonstring
* JSON text
* @param mainClass
* Primary entity type
* @param detailName1
* Attributes from the entity class in the primary entity class
* @param detailClass1
* FROM entity type
* @param detailName2
* Attributes from the entity class in the primary entity class
* @param detailClass2
* FROM entity type
* @param detailName3
* Attributes from the entity class in the primary entity class
* @param DETAILCLASS3
* FROM entity type
* @return
*/
public static <t, D1, D2, d3> T Tobean (String jsonstring,
Class<t> MainClass, String detailName1, class<d1> DetailClass1,
String detailName2, Class<d2> detailClass2, String DetailName3,
Class<d3> detailClass3) {
Jsonobject jsonobject = Jsonobject.fromobject (jsonstring);
Jsonarray jsonArray1 = (jsonarray) jsonobject.get (detailName1);
Jsonarray jsonArray2 = (jsonarray) jsonobject.get (detailName2);
Jsonarray jsonArray3 = (jsonarray) jsonobject.get (DETAILNAME3);

T mainentity = Tobean (Jsonobject, MainClass);
list<d1> detailList1 = toList (JsonArray1, DETAILCLASS1);
list<d2> detailList2 = toList (JsonArray2, DETAILCLASS2);
list<d3> detailList3 = toList (JsonArray3, DETAILCLASS3);

try {
Beanutils.setproperty (mainentity, detailName1, DetailList1);
Beanutils.setproperty (mainentity, detailName2, DetailList2);
Beanutils.setproperty (mainentity, DetailName3, DETAILLIST3);
} catch (Exception ex) {
throw new RuntimeException ("Master-Detail JSON deserialization entity failed!") ");
}

return mainentity;
}

/***************************************************************************
* Deserialize JSON text as the entity from the relationship
*
* @param <T>
* Primary entity type
* @param jsonstring
* JSON text
* @param mainClass
* Primary entity type
* @param detailclass
* Store multiple attribute names and types from entities in the primary entity
* @return
*/
public static <T> T Tobean (String jsonstring, class<t> MainClass,
Hashmap<string, class> Detailclass) {
Jsonobject jsonobject = Jsonobject.fromobject (jsonstring);
T mainentity = Tobean (Jsonobject, MainClass);
For (Object Key:detailClass.keySet ()) {
try {
Class value = (Class) Detailclass.get (key);
Beanutils.setproperty (Mainentity, key.tostring (), value);
} catch (Exception ex) {
throw new RuntimeException ("Master-Detail JSON deserialization entity failed!") ");
}
}
return mainentity;
}

public static string ToXML (String reportname,list List) {
New A StringBuilder is used to receive the XML value to be passed
StringBuilder Strbder = new StringBuilder ();
PrintWriter writer = null;

String resultname = null;
String resultcount = null;

Strbder.append ("<?xml version=\" 1.0\ "encoding=\" utf-8\ "?>");
Strbder.append ("<graph caption=\" "+reportname+" \ "" +
"Shownames=\" 1\ "decimalprecision=\" 1\ "numberformatscale=\" 1\ "basefontsize=\" 14\ "" +
"Formatnumber=\" 1\ "showvalues=\" 0\ ">");

for (int i=0;i<list.size (); i++) {
Map Currmap = (map) list.get (i);
Resultname = Currmap.get ("Resultname"). ToString ();

Resultcount = Currmap.get ("Resultcount"). ToString ();

Strbder.append ("<set name=\" "+resultname+" \ "value=\" "+resultcount+" \ "/>");

}

Strbder.append ("</graph>");
return strbder.tostring ();
}

JAVA && JSON

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.