由于本人最近在写webservice,之前一直都同通过AJAX,在服务端处理业务,但是最近需要写一些接口给其他人用,需要使用jsno的序列化与反序列化,什么是jsno就不多说,jsno的好处也不多说,直接贴代码。

1.需要引用System.Web.Script.Serialization;

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; using System.Web.Script.Serialization;
using System.Data; //后面用到DataTable

2.先说把对象转换成JSNO字符串。首先对象转JSON

 /// <summary>
/// 对象转JSON
/// </summary>
/// <param name="obj">对象</param>
/// <returns>JSON格式的字符串</returns>
public static string ObjectToJSON(object obj)
{
JavaScriptSerializer jss =new JavaScriptSerializer();
try
{
return jss.Serialize(obj);
}
catch(Exception ex)
{ throw new Exception("JSONHelper.ObjectToJSON(): "+ ex.Message);
}
}

3.DataTable dt数据集转换成JSNO字符串,需要将数据集DataTable转换成值对集合,才能通过对象转换成JSNO字符串

     /// 数据表转键值对集合
public static List<Dictionary<string,object>> DataTableToList(DataTable dt)
{
List<Dictionary<string,object>> list=new List<Dictionary<string,object>>(); foreach(DataRow dr in dt.Rows)
{
Dictionary<string,object> dic =new Dictionary<string,object>();
foreach(DataColumn dc in dt.Columns)
{
dic.Add(dc.ColumnName, dr[dc.ColumnName]);
}
list.Add(dic);
}
return list;
} // 数据表转JSON
public static string DataTableToJSON(DataTable dt)
{
return ObjectToJSON(DataTableToList(dt));
}

4.JSON文本转对象,泛型方法

  public static T JSONToObject<T>(string jsonText)
{
JavaScriptSerializer jss =new JavaScriptSerializer();
try
{
return jss.Deserialize<T>(jsonText);
}
catch(Exception ex)
{
throw new Exception("JSONHelper.JSONToObject(): "+ ex.Message);
}
}

5.将JSON文本转换为数据表数据

 public static Dictionary<string,List<Dictionary<string,object>>> TablesDataFromJSON(string jsonText)
{
return JSONToObject <Dictionary<string,List<Dictionary<string,object>>>>(jsonText);
}
04-30 03:03