JSON Tool Class

Source: Internet
Author: User

Using Newtonsoft.json;
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Linq;
Using System.Text;
Using System.Text.RegularExpressions;

public class Datatojson
{
<summary>
Serialize object object to JSON string
</summary>
<param name= "obj" > example of a sequence session </param>
<returns> serializing JSON strings </returns>
public static string Serializetojson (Object obj)
{
return Jsonconvert.serializeobject (obj);
}

<summary>
Deserializes JSON strings into object objects
</summary>
<param name= "JSON" >json string </param>
<returns> Object Instances </returns>
public static Object Deserializefromjson (string json)
{
Return Jsonconvert.deserializeobject (JSON);
}

<summary>
Deserializes a JSON string into a generic t
</summary>
<typeparam name= "T" > Generics </typeparam>
<param name= "JSON" >json string </param>
<returns> Generics-t</returns>
public static T deserializefromjson<t> (string json)
{
Return jsonconvert.deserializeobject<t> (JSON);
}
<summary>
Returns the JSON format used by the DataGrid in Easyui/extjs
</summary>
<param name= "DT" >datatable data </param>
<param name= "Count" > Total number of bars </param>
<returns></returns>
public static string Datatabletojson (DataTable dt, int count)
{
StringBuilder Sbjson = new StringBuilder ();
Sbjson. Append ("{");
Sbjson. Append ("\" total\ ":" + count + ", \" rows\ ": [");
if (dt! = NULL)
{
for (int i = 0; i < dt. Rows.Count; i++)
{
if (i > 0)
{
Sbjson. Append (",");
Sbjson. Append ("{");
foreach (DataColumn dc in dt. Columns)
{
String value = Stringplus.htmlencode (dt. ROWS[I][DC. ColumnName]. ToString (). Trim ());
if (dt. Columns.indexof (DC) > 0)
{
Sbjson. Append (",");
Sbjson. Append ("\" "+ DC.) ColumnName + "\": \ "" + Value + "\" ");
}
Else
{
Sbjson. Append ("\" "+ DC.) ColumnName + "\": \ "" + Value + "\" ");
}
}
Sbjson. Append ("}");
}
Else
{
Sbjson. Append ("{");
foreach (DataColumn dc in dt. Columns)
{
String value = Stringplus.htmlencode (dt. ROWS[I][DC. ColumnName]. ToString (). Trim ());
if (dt. Columns.indexof (DC) > 0)
{
Sbjson. Append (",");
Sbjson. Append ("\" "+ DC.) ColumnName + "\": \ "" + Value + "\" ");
}
Else
{
Sbjson. Append ("\" "+ DC.) ColumnName + "\": \ "" + Value + "\" ");
}
}
Sbjson. Append ("}");
}
}
}
Sbjson. Append ("]}");

Return Sbjson. ToString ();
}

<summary>
Generating a JSON tree structure from a DataTable
</summary>
<param name= "tabel" > Data source </param>
<param name= "Idcol" >id column </param>
<param name= "Txtcol" >text column </param>
<param name= "RelA" > Relationship fields </param>
<param name= "PId" > Parent id</param>
public static string Gettreejsonbytable (DataTable tabel, String idcol, String Txtcol, String RelA, Object pId)
{
String rlt = "";
StringBuilder result = new StringBuilder ();
StringBuilder sb = new StringBuilder ();
Result. Append (sb.) ToString ());
Sb. Length = 0;
if (tabel. Rows.Count > 0)
{
Sb. Append ("[");
string filer = string. Format ("{0}= ' {1} '", RelA, PId);
datarow[] rows = tabel. Select (filer);
if (rows. Length > 0)
{
foreach (DataRow row in rows)
{
Sb. Append ("{\" id\ ": \" "+ Row[idcol] +" \ ", \" text\ ": \" "+ Row[txtcol] +" \ ", \" state\ ": \" open\ "");
if (tabel. Select (String. Format ("{0}= ' {1} '", RelA, Row[idcol]). Length > 0)
{
Sb. Append (", \" children\ ":");
Gettreejsonbytable (Tabel, Idcol, Txtcol, RelA, Row[idcol]);
Result. Append (sb.) ToString ());
Sb. Length = 0;
}
Result. Append (sb.) ToString ());
Sb. Length = 0;
Sb. Append ("},");
}
SB = sb. Remove (sb.) Length-1, 1);
}
Sb. Append ("]");
Result. Append (sb.) ToString ());
RLT = result. ToString ();
Sb. Length = 0;
}
return RLT;
}

#region JSON to DataTable
<summary>
Returns the Datetable,json data format according to JSON, such as:
{Table:[{column1:1,column2:2,column3:3},{column1:1,column2:2,column3:3}]}
</summary>
<param name= "Strjson" >json string </param>
<returns></returns>
public static DataTable jsontodatatable (String Strjson)
{
Remove Table name
var rg = new Regex (@ "(? <={) [^:]+ (? =:\[)", regexoptions.ignorecase);
String strName = RG. Match (Strjson). Value;
DataTable TB = null;
Remove Table name
Strjson = strjson.substring (Strjson.indexof ("[") + 1);
Strjson = strjson.substring (0, Strjson.indexof ("]"));

Get Data
RG = new Regex (@ "(? <={) [^}]+ (? =})");
MatchCollection MC = RG. Matches (Strjson);
for (int i = 0; I < MC. Count; i++)
{
String strrow = Mc[i]. Value;
string[] strrows = Strrow.split (', ');

Create a table
if (TB = = NULL)
{
TB = new DataTable ();
Tb. TableName = StrName;
foreach (String str in strrows)
{
var dc = new DataColumn ();
string[] Strcell = str. Split (': ');
dc. ColumnName = strcell[0];
Tb. Columns.Add (DC);
}
Tb. AcceptChanges ();
}

Add content
DataRow dr = TB. NewRow ();
for (int r = 0; r < strrows.length; r++)
{
DR[R] = Strrows[r]. Split (': ') [1]. Trim (). Replace (",", ","). Replace (":", ":"). Replace ("\" "," ");
}
Tb. Rows.Add (DR);
Tb. AcceptChanges ();
}

return TB;
}
#endregion

#region Generating Easyui tree JSON structure from a DataTable
<summary>
Generate a Easyui tree JSON structure based on a DataTable
</summary>
<param name= "tabel" > Data source </param>
<param name= "Idcol" >id column </param>
<param name= "Txtcol" >text column </param>
<param name= "url" > Node url</param>
<param name= "RelA" > Relationship fields </param>
<param name= "PId" > Parent id</param>
<example>string JSON = gettreejsonbytable (DT, "id", "name", "url", "Fatherid", "0");</example>
private string Gettreejsonbytable (DataTable tabel, String idcol, String txtcol, String url, String rela, Object pId)
{
StringBuilder result = new StringBuilder ();
StringBuilder sb = new StringBuilder ();
Result. Append (sb.) ToString ());
Sb. Length = 0;
if (tabel. Rows.Count > 0)
{
Sb. Append ("[");
string filer = string. Format ("{0}= ' {1} '", RelA, PId);
datarow[] rows = tabel. Select (filer);
if (rows. Length > 0)
{
foreach (DataRow row in rows)
{
Sb. Append ("{\" id\ ": \" "+ Row[idcol] +" \ ", \" text\ ": \" "+ Row[txtcol] +" \ ", \" attributes\ ": \" "+ row[url" + "\", \ "state\": \ "Op En\ "");
if (tabel. Select (String. Format ("{0}= ' {1} '", RelA, Row[idcol]). Length > 0)
{
Sb. Append (", \" children\ ":");
Gettreejsonbytable (Tabel, Idcol, Txtcol, URL, RelA, Row[idcol]);
Result. Append (sb.) ToString ());
Sb. Length = 0;
}
Result. Append (sb.) ToString ());
Sb. Length = 0;
Sb. Append ("},");
}
SB = sb. Remove (sb.) Length-1, 1);
}
Sb. Append ("]");
Result. Append (sb.) ToString ());
Sb. Length = 0;
}
return result. ToString ();
}
#endregion

}

JSON Tool Class

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.