Benefits of Android Json

Source: Internet
Author: User
Tags tojson

Import java. lang. reflect. Method;
Import java. util. Collection;
Import java. util. Map;
Import java. util. Set;
Public final class JsonUtil
{
/**
* Encapsulate an object in JSON format
*
* @ Param o
* Object
* @ Return JSON format
*/
@ SuppressWarnings ("unchecked ")
Public static String toJson (final Object o)
{
If (o = null)
{
Return "null ";
}
If (o instanceof String) // String
{
Return string2Json (String) o );
}
If (o instanceof Boolean) // Boolean
{
Return boolean2Json (Boolean) o );
}
If (o instanceof Number) // Number
{
Return number2Json (Number) o );
}
If (o instanceof Map) // Map
{
Return map2Json (Map <String, Object>) o );
}
If (o instanceof Collection) // List Set
{
Return collection2Json (Collection) o );
}
If (o instanceof Object []) // Object Array
{
Return array2Json (Object []) o );
}
If (o instanceof int []) // array of Basic Types
{
Return intArray2Json (int []) o );
}
If (o instanceof boolean []) // basic type array
{
Return booleanArray2Json (boolean []) o );
}
If (o instanceof long []) // basic type array
{
Return longArray2Json (long []) o );
}
If (o instanceof float []) // basic type array
{
Return floatArray2Json (float []) o );
}
If (o instanceof double []) // basic type array
{
Return doubleArray2Json (double []) o );
}
If (o instanceof short []) // array of Basic Types
{
Return shortArray2Json (short []) o );
}
If (o instanceof byte []) // array of Basic Types
{
Return byteArray2Json (byte []) o );
}
If (o instanceof Object) // The end Object
{
Return object2Json (o );
}
Throw new RuntimeException ("unsupported type:" + o. getClass (). getName ());
}
/**
* Encode a String object in JSON format. You only need to process special characters.
*
* @ Param s
* String object
* @ Return JSON format
*/
Static String string2Json (final String s)
{
Final StringBuilder sb = new StringBuilder (s. length () + 20 );
Sb. append ('\"');
For (int I = 0; I <s. length (); I ++)
{
Final char c = s. charAt (I );
Switch (c)
{
Case '\"':
Sb. append ("\\\"");
Break;
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;
Default:
Sb. append (c );
}
}
Sb. append ('\"');
Return sb. toString ();
}
/**
* Indicates the Number in JSON format.
*
* @ Param number
* Number
* @ Return JSON format
*/
Static String number2Json (final Number number)
{
Return number. toString ();
}
/**
* Boolean is represented in JSON format.
*
* @ Param bool
* Boolean
* @ Return JSON format
*/
Static String boolean2Json (final Boolean bool)
{
Return bool. toString ();
}
/**
* Encode the Collection into JSON format (List, Set)
*
* @ Param c
* @ Return
*/
Static String collection2Json (final Collection <Object> c)
{
Final Object [] arrObj = c. toArray ();
Return toJson (arrObj );
}
/**
* Encode Map <String, Object> In JSON format
*
* @ Param map
* @ Return
*/
Static String map2Json (final Map <String, Object> map)
{
If (map. isEmpty ())
{
Return "{}";
}
Final StringBuilder sb = new StringBuilder (map. size () <4); // 4 th power
Sb. append ('{');
Final Set <String> keys = map. keySet ();
For (final String key: keys)
{
Final Object value = map. get (key );
Sb. append ('\"');
Sb. append (key); // cannot contain special characters
Sb. append ('\"');
Sb. append (':');
Sb. append (toJson (value); // The object referenced cyclically will lead to infinite Recursion
Sb. append (',');
}
// Change the last ',' '}':
Sb. setCharAt (sb. length ()-1 ,'}');
Return sb. toString ();
}
/**
* Encode arrays in JSON format
*
* @ Param array
* Array
* @ Return JSON format
*/
Static String array2Json (final Object [] array)
{
If (array. length = 0)
{
Return "[]";
}
Final StringBuilder sb = new StringBuilder (array. length <4); // 4 Power
Sb. append ('[');
For (final Object o: array)
{
Sb. append (toJson (o ));
Sb. append (',');
}
// Change the last ',' to ']':
Sb. setCharAt (sb. length ()-1, ']');
Return sb. toString ();
}
Static String intArray2Json (final int [] array)
{
If (array. length = 0)
{
Return "[]";
}
Final StringBuilder sb = new StringBuilder (array. length <4 );
Sb. append ('[');
For (final int o: array)
{
Sb. append (Integer. toString (o ));
Sb. append (',');
}
// Set last', 'to'] ':
Sb. setCharAt (sb. length ()-1, ']');
Return sb. toString ();
}
Static String longArray2Json (final long [] array)
{
If (array. length = 0)
{
Return "[]";
}
Final StringBuilder sb = new StringBuilder (array. length <4 );
Sb. append ('[');
For (final long o: array)
{
Sb. append (Long. toString (o ));
Sb. append (',');
}
// Set last', 'to'] ':
Sb. setCharAt (sb. length ()-1, ']');
Return sb. toString ();
}
Static String booleanArray2Json (final boolean [] array)
{
If (array. length = 0)
{
Return "[]";
}
Final StringBuilder sb = new StringBuilder (array. length <4 );
Sb. append ('[');
For (final boolean o: array)
{
Sb. append (Boolean. toString (o ));
Sb. append (',');
}
// Set last', 'to'] ':
Sb. setCharAt (sb. length ()-1, ']');
Return sb. toString ();
}
Static String floatArray2Json (final float [] array)
{
If (array. length = 0)
{
Return "[]";
}
Final StringBuilder sb = new StringBuilder (array. length <4 );
Sb. append ('[');
For (final float o: array)
{
Sb. append (Float. toString (o ));
Sb. append (',');
}
// Set last', 'to'] ':
Sb. setCharAt (sb. length ()-1, ']');
Return sb. toString ();
}
Static String doubleArray2Json (final double [] array)
{
If (array. length = 0)
{
Return "[]";
}
Final StringBuilder sb = new StringBuilder (array. length <4 );
Sb. append ('[');
For (final double o: array)
{
Sb. append (Double. toString (o ));
Sb. append (',');
}
// Set last', 'to'] ':
Sb. setCharAt (sb. length ()-1, ']');
Return sb. toString ();
}
Static String shortArray2Json (final short [] array)
{
If (array. length = 0)
{
Return "[]";
}
Final StringBuilder sb = new StringBuilder (array. length <4 );
Sb. append ('[');
For (final short o: array)
{
Sb. append (Short. toString (o ));
Sb. append (',');
}
// Set last', 'to'] ':
Sb. setCharAt (sb. length ()-1, ']');
Return sb. toString ();
}
Static String byteArray2Json (final byte [] array)
{
If (array. length = 0)
{
Return "[]";
}
Final StringBuilder sb = new StringBuilder (array. length <4 );
Sb. append ('[');
For (final byte o: array)
{
Sb. append (Byte. toString (o ));
Sb. append (',');
}
// Set last', 'to'] ':
Sb. setCharAt (sb. length ()-1, ']');
Return sb. toString ();
}
Public static String object2Json (final Object bean)
{
// Data check
If (bean = null)
{
Return "{}";
}
Final Method [] methods = bean. getClass (). getMethods (); // Method Array
Final StringBuilder sb = new StringBuilder (methods. length <4); // 4 Power
Sb. append ('{');
For (final Method method: methods)
{
Try
{
Final String name = method. getName ();
String key = "";
If (name. startsWith ("get "))
{
Key = name. substring (3 );
// Prevents endless Loops
Final String [] arrs =
{"Class "};
Boolean bl = false;
For (final String s: arrs)
{
If (s. equals (key ))
{
Bl = true;
Continue;
}
}
If (bl)
{
Continue; // prevents endless Loops
}
}
Else if (name. startsWith ("is "))
{
Key = name. substring (2 );
}
If (key. length ()> 0 & Character. isUpperCase (key. charAt (0) & method. getParameterTypes (). length = 0)
{
If (key. length () = 1)
{
Key = key. toLowerCase ();
}
Else if (! Character. isUpperCase (key. charAt (1 )))
{
Key = key. substring (0, 1). toLowerCase () + key. substring (1 );
}
Final Object elementObj = method. invoke (bean );
// System. out. println ("###" + key + ":" + elementObj. toString ());
Sb. append ('\"');
Sb. append (key); // cannot contain special characters
Sb. append ('\"');
Sb. append (':');
Sb. append (toJson (elementObj); // The object referenced cyclically will lead to infinite Recursion
Sb. append (',');
}
}
Catch (final Exception e)
{
// E. getMessage ();
Throw new RuntimeException ("exception when bean is encapsulated into JSON format:" + e. getMessage (), e );
}
}
If (sb. length () = 1)
{
Return bean. toString ();
}
Else
{
Sb. setCharAt (sb. length ()-1 ,'}');
Return sb. toString ();
}
}
Private JsonUtil ()
{
}
}

Author: Feng jingbao

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.