ASP.NET之JSONHelper操作
之前说到了Ext.Net中GridPanel行取值的问题(Ext.Net开发_GridPanel行选中取值),涉及到checkBox操作时,要留个心眼注意下取值的区别!返回值是Json格式。 现在用到了Json,就想自己也整一个Josn帮助类。在线帮助的资料很多,在巨人的身上东凑西凑也凑一个用用。
一、介绍
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() + "