C葃JSONHelperのJson変換方法大全書
3219 ワード
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Data;
///
/// JSON
///
publicclassJSONHelper
{
///
/// JSON
///
///
/// JSON
publicstaticstringObjectToJSON(object obj)
{
JavaScriptSerializer jss =newJavaScriptSerializer();
try
{
return jss.Serialize(obj);
}
catch(Exception ex)
{
thrownewException("JSONHelper.ObjectToJSON(): "+ ex.Message);
}
}
///
/// www.2cto.com
/// DataTable List ,
/// ,
///
///
///
publicstaticList>DataTableToList(DataTable dt)
{
List> list
=newList>();
foreach(DataRow dr in dt.Rows)
{
Dictionary dic =newDictionary();
foreach(DataColumn dc in dt.Columns)
{
dic.Add(dc.ColumnName, dr[dc.ColumnName]);
}
list.Add(dic);
}
return list;
}
///
///
///
///
///
publicstaticDictionary>>DataSetToDic(DataSet ds)
{
Dictionary>> result =newDictionary>>();
foreach(DataTable dt in ds.Tables)
result.Add(dt.TableName,DataTableToList(dt));
return result;
}
///
/// JSON
///
///
/// JSON
publicstaticstringDataTableToJSON(DataTable dt)
{
returnObjectToJSON(DataTableToList(dt));
}
///
/// JSON ,
///
///
/// JSON
///
publicstatic T JSONToObject(string jsonText)
{
JavaScriptSerializer jss =newJavaScriptSerializer();
try
{
return jss.Deserialize(jsonText);
}
catch(Exception ex)
{
thrownewException("JSONHelper.JSONToObject(): "+ ex.Message);
}
}
///
/// JSON
///
/// JSON
///
publicstaticDictionary>>TablesDataFromJSON(string jsonText)
{
returnJSONToObject>>>(jsonText);
}
///
/// JSON
///
/// JSON
///
publicstaticDictionaryDataRowFromJSON(string jsonText)
{
returnJSONToObject>(jsonText);
}
}