ASP. NET converts an object to a JSON string

Source: Internet
Author: User
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;
Using system. text;
Using system. reflection;
Using system. collections;
Using system. Data;
Using system. Data. Common;

/// <Summary>
/// Summary description for tojson
/// </Summary>
Public class objecttojson
{
Public objecttojson ()
{
//
// Todo: Add constructor logic here
//
}

/// <Summary>
/// Convert list to JSON
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "jsonname"> </param>
/// <Param name = "list"> </param>
/// <Returns> </returns>
Public static string listtojson <t> (ilist <t> list, string jsonname)
{
Stringbuilder JSON = new stringbuilder ();
If (string. isnullorempty (jsonname ))
Jsonname = list [0]. GetType (). Name;
JSON. append ("{\" "+ jsonname + "\":[");
If (list. Count> 0)
{
For (INT I = 0; I <list. Count; I ++)
{
T OBJ = activator. createinstance <t> ();
Propertyinfo [] Pi = obj. GetType (). getproperties ();
JSON. append ("{");
For (Int J = 0; j <pi. length; j ++)
{
Type type = PI [J]. getvalue (list [I], null). GetType ();
JSON. append ("\" "+ PI [J]. name. tostring () + "\": "+ stringformat (PI [J]. getvalue (list [I], null ). tostring (), type ));

If (j <pi. Length-1)
{
JSON. append (",");
}
}
JSON. append ("}");
If (I <list. Count-1)
{
JSON. append (",");
}
}
}
JSON. append ("]}");
Return JSON. tostring ();
}

/// <Summary>
/// Convert list to JSON
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "list"> </param>
/// <Returns> </returns>
Public static string listtojson <t> (ilist <t> List)
{
Object OBJ = list [0];
Return listtojson <t> (list, obj. GetType (). Name );
}

/// <Summary>
/// Convert an object to a JSON string
/// </Summary>
/// <Param name = "jsonobject"> Object </param>
/// <Returns> JSON string </returns>
Public static string tojson (Object jsonobject)
{
String jsonstring = "{";
Propertyinfo [] propertyinfo = jsonobject. GetType (). getproperties ();
For (INT I = 0; I <propertyinfo. length; I ++)
{
Object objectvalue = propertyinfo [I]. getgetmethod (). Invoke (jsonobject, null );
String value = string. empty;
If (objectvalue is datetime | objectvalue is guid | objectvalue is timespan)
{
Value = "'" + objectvalue. tostring () + "'";
}
Else if (objectvalue is string)
{
Value = "'" + tojson (objectvalue. tostring () + "'";
}
Else if (objectvalue is ienumerable)
{
Value = tojson (ienumerable) objectvalue );
}
Else
{
Value = tojson (objectvalue. tostring ());
}
Jsonstring + = "\" "+ tojson (propertyinfo [I]. Name) +" \ ":" + value + ",";
}
Jsonstring. Remove (jsonstring. Length-1, jsonstring. Length );
Return jsonstring + "}";
}

/// <Summary>
/// Convert the object set to JSON
/// </Summary>
/// <Param name = "array"> set object </param>
/// <Returns> JSON string </returns>
Public static string tojson (ienumerable array)
{
String jsonstring = "[";
Foreach (Object item in array)
{
Jsonstring + = tojson (item) + ",";
}
Jsonstring. Remove (jsonstring. Length-1, jsonstring. Length );
Return jsonstring + "]";
}

/// <Summary>
/// Convert a common set to JSON
/// </Summary>
/// <Param name = "array"> set object </param>
/// <Returns> JSON string </returns>
Public static string toarraystring (ienumerable array)
{
String jsonstring = "[";
Foreach (Object item in array)
{
Jsonstring = tojson (item. tostring () + ",";
}
Jsonstring. Remove (jsonstring. Length-1, jsonstring. Length );
Return jsonstring + "]";
}

/// <Summary>
/// Datatable converted to JSON
/// </Summary>
/// <Param name = "table"> datatable object </param>
/// <Returns> JSON string </returns>
Public static string tojson (datatable DT)
{
Stringbuilder jsonstring = new stringbuilder ();
Jsonstring. append ("[");
Datarowcollection DRC = DT. Rows;
For (INT I = 0; I <DRC. Count; I ++)
{
Jsonstring. append ("{");
For (Int J = 0; j <DT. Columns. Count; j ++)
{
String strkey = DT. Columns [J]. columnname;
String strvalue = DRC [I] [J]. tostring ();
Type type = DT. Columns [J]. datatype;
Jsonstring. append ("\" "+ strkey + "\":");
Strvalue = stringformat (strvalue, type );
If (j <DT. Columns. Count-1)
{
Jsonstring. append (strvalue + ",");
}
Else
{
Jsonstring. append (strvalue );
}
}
Jsonstring. append ("},");
}
Jsonstring. Remove (jsonstring. Length-1, 1 );
Jsonstring. append ("]");
Return jsonstring. tostring ();
}

/// <Summary>
/// Convert the datatable to JSON
/// </Summary>
/// <Param name = "jsonname"> </param>
/// <Param name = "DT"> </param>
/// <Returns> </returns>
Public static string tojson (datatable DT, string jsonname)
{
Stringbuilder JSON = new stringbuilder ();
If (string. isnullorempty (jsonname ))
Jsonname = DT. tablename;
JSON. append ("{\" "+ jsonname + "\":[");
If (Dt. Rows. Count> 0)
{
For (INT I = 0; I <DT. Rows. Count; I ++)
{
JSON. append ("{");
For (Int J = 0; j <DT. Columns. Count; j ++)
{
Type type = DT. Rows [I] [J]. GetType ();
JSON. append ("\" "+ dt. columns [J]. columnname. tostring () + "\": "+ stringformat (DT. rows [I] [J]. tostring (), type ));
If (j <DT. Columns. Count-1)
{
JSON. append (",");
}
}
JSON. append ("}");
If (I <DT. Rows. Count-1)
{
JSON. append (",");
}
}
}
JSON. append ("]}");
Return JSON. tostring ();
}

/// <Summary>
/// Convert datareader to JSON
/// </Summary>
/// <Param name = "datareader"> datareader object </param>
/// <Returns> JSON string </returns>
Public static string tojson (dbdatareader datareader)
{
Stringbuilder jsonstring = new stringbuilder ();
Jsonstring. append ("[");
While (datareader. Read ())
{
Jsonstring. append ("{");
For (INT I = 0; I <datareader. fieldcount; I ++)
{
Type type = datareader. getfieldtype (I );
String strkey = datareader. getname (I );
String strvalue = datareader [I]. tostring ();
Jsonstring. append ("\" "+ strkey + "\":");
Strvalue = stringformat (strvalue, type );
If (I <datareader. fieldcount-1)
{
Jsonstring. append (strvalue + ",");
}
Else
{
Jsonstring. append (strvalue );
}
}
Jsonstring. append ("},");
}
Datareader. Close ();
Jsonstring. Remove (jsonstring. Length-1, 1 );
Jsonstring. append ("]");
Return jsonstring. tostring ();
}

/// <Summary>
/// Convert dataset to JSON
/// </Summary>
/// <Param name = "dataset"> DataSet object </param>
/// <Returns> JSON string </returns>
Public static string tojson (Dataset dataset)
{
String jsonstring = "{";
Foreach (datatable table in dataset. Tables)
{
Jsonstring + = "\" "+ Table. tablename +" \ ":" + tojson (table) + ",";
}
Jsonstring = jsonstring. trimend (',');
Return jsonstring + "}";
}

/// <Summary>
/// Filter special characters
/// </Summary>
/// <Param name = "S"> </param>
/// <Returns> </returns>
Private Static string string2json (string S)
{
Stringbuilder sb = new stringbuilder ();
For (INT I = 0; I <S. length; I ++)
{
Char c = S. tochararray () [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); break;
}
}
Return sb. tostring ();
}

/// <Summary>
/// Format String, date, and Boolean
/// </Summary>
/// <Param name = "str"> </param>
/// <Param name = "type"> </param>
/// <Returns> </returns>
Private Static string stringformat (string STR, type)
{
If (type = typeof (string ))
{
STR = string2json (STR );
STR = "\" "+ STR + "\"";
}
Else if (type = typeof (datetime ))
{
STR = "\" "+ STR + "\"";
}
Else if (type = typeof (bool ))
{
STR = Str. tolower ();
}
Return STR;
}

}

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.