C#對象轉JSON字符串和JSON字符串轉對象
/* 創建者:菜刀居士的博客
* 創建日期: 2014年09月03號
* 功能: Json操作
*
*/
namespace Net.String.ConsoleApplication
{
using System;
using System.Data;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class JsonHelper
{
/// <summary>
/// 把json字符串轉成對象
/// </summary>
/// <typeparam name="T">對象</typeparam>
/// <param name="data">json字符串</param>
public static T Deserialize<T>(string data)
{
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
return json.Deserialize<T>(data);
}
/// <summary>
/// 把對象轉成json字符串
/// </summary>
/// <param name="o">對象</param>
/// <returns>json字符串</returns>
public static string Serialize(object o)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
json.Serialize(o, sb);
return sb.ToString();
}
/// <summary>
/// 把DataTable對象轉成json字符串
/// </summary>
public string ToJson(DataTable dt)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
ArrayList arrayList = new ArrayList();
foreach (DataRow dataRow in dt.Rows)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (DataColumn dataColumn in dt.Columns)
{
dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName]);
}
arrayList.Add(dictionary);
}
return javaScriptSerializer.Serialize(arrayList);
}
}
public static class EnumerableExtension
{
/// <summary>
/// 集合添加一個對象
/// </summary>
public static IEnumerable<T> Add<T>(this IEnumerable<T> e, T value)
{
foreach (var cur in e)
{ yield return cur; }
yield return value;
}
/// <summary>
/// 把集合轉成DataTable
/// </summary>
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> enumerable)
{
var dataTable = new DataTable();
foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(T)))
{
dataTable.Columns.Add(pd.Name, pd.PropertyType);
}
foreach (T item in enumerable)
{
var Row = dataTable.NewRow();
foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
{
Row[dp.Name] = dp.GetValue(item);
}
dataTable.Rows.Add(Row);
}
return dataTable;
}
}
}
C#多線程編程實例 線程與窗體交互【附源碼】 http://www.linuxidc.com/Linux/2014-07/104294.htm
C#數學運算表達式解釋器 http://www.linuxidc.com/Linux/2014-07/104289.htm
在C語言中解析JSON配置文件 http://www.linuxidc.com/Linux/2014-05/101822.htm
C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm