一、介紹
JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式,基於JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一個子集
方法有多種,我這邊用到是DataContractJsonSerializer類,官方解釋:“NET Framework 4 .NET Framework 3.5 Silverlight 將物件序列化為 JavaScript 物件表示法 (JSON),並將 JSON 資料反序列化為物件”。
其名稱空間如下:
注意:如果是.NET Framework 3.5 光引用了“System.Runtime.Serialization”了這個還不行。執行時會發現:
所以還要引用下“System.ServiceModel.Web”即可。 .NET Framework 4則在System.Runtime.Serialization下。
二、對JSON資料操作
原始碼:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
namespace WebUI.CommonClass
{
public class JSONHelper
{
/// <summary>
/// JSON序列化
/// </summary>
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
//替換Json的Date字串
string p = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
}
/// <summary>
/// JSON反序列化
/// </summary>
public static T JsonDeserialize<T>(string jsonString)
{
//將"yyyy-MM-dd HH:mm:ss"格式的字串轉為"\/Date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
/// <summary>
/// 將Json序列化的時間由/Date(1294499956278+0800)轉為字串
/// </summary>
private static string ConvertJsonDateToDateString(Match m)
{
string result = string.Empty;
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
dt = dt.ToLocalTime();
result = dt.ToString("yyyy-MM-dd HH:mm:ss");
return result;
}
/// <summary>
/// 將時間字串轉為Json時間
/// </summary>
private static string ConvertDateStringToJsonDate(Match m)
{
string result = string.Empty;
DateTime dt = DateTime.Parse(m.Groups[0].Value);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - DateTime.Parse("1970-01-01");
result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
return result;
}
}
}
實驗下:
Product
public class Product
{
public string proName { get ;set ; }
public decimal proPrice { get; set; }
public string proAttr { get; set; }
public string proAddres { get; set; }
}
操作
1:序列化
Product pro = new Product();
pro.proAddres = "上海";
pro.proAttr = "cpu";
pro.proName = "電腦";
pro.proPrice = 3680;
string josn = JSONHelper.JsonSerializer<Product>(pro); //序列化
Message.ShowAlert("提示", josn);
效果:
2,反序列化
string json = "{\"proAddres\":\"上海\",\"proAttr\":\"cpu\",\"proName\":\"電腦\",\"proPrice\":3680}";
Product pro = JSONHelper.JsonDeserialize<Product>(json);
JSONHELP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections;
using System.Data;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.Text.RegularExpressions;
namespace FumaCRM_BS.NewWeb.Common.Class
{
public class JsonHelper
{
/// <summary>
/// DataTable轉Json
/// </summary>
/// <param name="dtb"></param>
/// <returns></returns>
public static string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = new ArrayList();
foreach (DataRow row in dtb.Rows)
{
Dictionary<string, object> drow = new Dictionary<string, object>();
foreach (DataColumn col in dtb.Columns)
{
drow.Add(col.ColumnName, row[col.ColumnName]);
}
dic.Add(drow);
}
return jss.Serialize(dic);
}
/// <summary>
/// Json轉DataTable
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static DataTable Json2Dtb(string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = jss.Deserialize<ArrayList>(json);
DataTable dtb = new DataTable();
if (dic.Count > 0)
{
foreach (Dictionary<string, object> drow in dic)
{
if (dtb.Columns.Count == 0)
{
foreach (string key in drow.Keys)
{
//if (drow[key].GetType() != null)
// dtb.Columns.Add(key, drow[key].GetType());
//else
dtb.Columns.Add(key);
}
}
DataRow row = dtb.NewRow();
foreach (string key in drow.Keys)
{
row[key] = drow[key];
}
dtb.Rows.Add(row);
}
}
return dtb;
}
public static string DataTable2Json(DataTable dt)
{
if (dt == null || dt.Rows.Count == 0)
return "[]";
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":\"");
string value = dt.Rows[i][j].ToString().Replace("\r", "").Replace("\n", "").Replace("\t", "").Trim();
if (dt.Columns[j].DataType.FullName == "System.DateTime")
jsonBuilder.Append(value.Length == 0 ? value : Convert.ToDateTime(value).ToString("yyyy-MM-dd"));
else
jsonBuilder.Append(value);
jsonBuilder.Append("\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
return jsonBuilder.ToString();
}
#region JqueryEasyUI JSON Method
/// <summary>
/// 生成表單編輯賦值 JSON格式
/// </summary>
/// <param name="dt"></param>
/// <param name="displayCount"></param>
/// <returns></returns>
public static string CreateJsonOne(DataTable dt, bool displayCount)
{
StringBuilder JsonString = new StringBuilder();
//Exception Handling
if (dt != null && dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
JsonString.Append("{ ");
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - 1)
{
JsonString.Append("ipt_" + dt.Columns[j].ColumnName.ToString().ToLower() + ":" + "\"" + dt.Rows[i][j].ToString() + "\","