·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> C#操作json类型数据

C#操作json类型数据

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

将对象序列化为 javaScript 对象表示法 (JSON),并将 JSON 数据反序列化为对象。 此类不能继承。

//  msdn 例子:

 

[csharp] view plaincopy
  1. namespace SL_DataContractJsonSerializer  
  2. {  
  3.     public partial class Page : UserControl  
  4.     {  
  5.         public Page()  
  6.         {  
  7.             InitializeComponent();  
  8.         }  
  9.   
  10.         //This uses an event handler, not SL data binding  
  11.         void OnClick(object sender, EventArgs args)  
  12.         {  
  13.             txtOutput1.Text = "Create a User object and serialize it.";  
  14.             string json = WriteFromObject();  
  15.             txtOutput2.Text = json.ToString(); // Displays: {"Age":42,"Name":"Bob"}  
  16.   
  17.             txtOutput3.Text = "Deserialize the data to a User object.";  
  18.             string jsonString = "{'Name':'Bill', 'Age':53}";  
  19.             User deserializedUser = ReadToObject(jsonString);  
  20.             txtOutput4.Text = deserializedUser.Name; // Displays: Bill  
  21.             txtOutput5.Text = deserializedUser.Age.ToString(); // Displays: 53  
  22.         }  
  23.         // Create a User object and serialize it to a JSON stream.  
  24.         public static string WriteFromObject()  
  25.         {  
  26.             //Create User object.  
  27.             User user = new User("Bob", 42);  
  28.   
  29.             //Create a stream to serialize the object to.  
  30.             MemoryStream ms = new MemoryStream();  
  31.   
  32.             // Serializer the User object to the stream.  
  33.             DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));  
  34.             ser.WriteObject(ms, user);  
  35.             byte[] json = ms.ToArray();  
  36.             ms.Close();  
  37.             return Encoding.UTF8.GetString(json, 0, json.Length);  
  38.   
  39.         }  
  40.   
  41.         // Deserialize a JSON stream to a User object.  
  42.         public static User ReadToObject(string json)  
  43.         {  
  44.             User deserializedUser = new User();  
  45.             MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));  
  46.             DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedUser.GetType());  
  47.             deserializedUser = ser.ReadObject(ms) as User;  
  48.             ms.Close();  
  49.             return deserializedUser;  
  50.         }  
  51.   
  52.     }  
  53.   
  54.     [DataContract]  
  55.     public class User  
  56.     {  
  57.         [DataMember]  
  58.         public string Name { get; set; }  
  59.   
  60.         [DataMember]  
  61.         public int Age { get; set; }  
  62.   
  63.         public User() { }  
  64.   
  65.         public User(string newName, int newAge)  
  66.         {  
  67.             Name = newName;  
  68.             Age = newAge;  
  69.         }  
  70.   
  71.     }  
  72.   
  73. }  


可以抽象成如下类:

 

 

[csharp] view plaincopy
  1. public class JsonHelper  
  2.     {  
  3.         /// <summary>  
  4.         /// 生成Json格式  
  5.         /// </summary>  
  6.         /// <typeparam name="T"></typeparam>  
  7.         /// <param name="obj"></param>  
  8.         /// <returns></returns>  
  9.         public static string GetJson<T>(T obj)  
  10.         {  
  11.             DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());  
  12.             using (MemoryStream stream = new MemoryStream())  
  13.             {  
  14.                 json.WriteObject(stream, obj);  
  15.                 string szJson = Encoding.UTF8.GetString(stream.ToArray());   
  16.                 return szJson;  
  17.             }  
  18.         }  
  19.         /// <summary>  
  20.         /// 获取Json的Model  
  21.         /// </summary>  
  22.         /// <typeparam name="T"></typeparam>  
  23.         /// <param name="szJson"></param>  
  24.         /// <returns></returns>  
  25.         public static T ParseFromJson<T>(string szJson)  
  26.         {  
  27.             T obj = Activator.CreateInstance<T>();  
  28.             using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))  
  29.             {  
  30.                 DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());  
  31.                 return (T)serializer.ReadObject(ms);  
  32.             }  
  33.         }  
  34.     }  

 

[csharp] view plaincopy
  1. /// <summary>  
  2.         /// 反回JSON数据到前台  
  3.         /// </summary>  
  4.         /// <param name="dt">数据表</param>  
  5.         /// <returns>JSON字符串</returns>  
  6.         public string DataTableToJson(DataTable dt)  
  7.         {  
  8.             StringBuilder JsonString = new StringBuilder();  
  9.             if (dt != null && dt.Rows.Count > 0)  
  10.             {  
  11.                 JsonString.Append("{ ");  
  12.                 JsonString.Append("\"TableInfo\":[ ");  
  13.                 for (int i = 0; i < dt.Rows.Count; i++)  
  14.                 {  
  15.                     JsonString.Append("{ ");  
  16.                     for (int j = 0; j < dt.Columns.Count; j++)  
  17.                     {  
  18.                         if (j < dt.Columns.Count - 1)  
  19.                         {  
  20.                             JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");  
  21.                         }  
  22.                         else if (j == dt.Columns.Count - 1)  
  23.                         {  
  24.                             JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");  
  25.                         }  
  26.                     }  
  27.                     if (i == dt.Rows.Count - 1)  
  28.                     {  
  29.                         JsonString.Append("} ");  
  30.                     }  
  31.                     else  
  32.                     {  
  33.                         JsonString.Append("}, ");  
  34.                     }  
  35.                 }  
  36.                 JsonString.Append("]}");  
  37.                 return JsonString.ToString();  
  38.             }  
  39.             else  
  40.             {  
  41.                 return null;  
  42.             }  
  43.         }  


//还有一种方式操作json类型数据:

 

 

[csharp] view plaincopy
  1. public static class JsonTableHelper  
  2.     {  
  3.         /// <summary>   
  4.         /// 返回对象序列化   
  5.         /// </summary>   
  6.         /// <param name="obj">源对象</param>   
  7.         /// <returns>json数据</returns>   
  8.         public static string ToJson(this object obj)  
  9.         {  
  10.             JavascriptSerializer serialize = new JavaScriptSerializer();  
  11.             return serialize.Serialize(obj);  
  12.         }  
  13.   
  14.         /// <summary>   
  15.         /// 控制深度   
  16.         /// </summary>   
  17.         /// <param name="obj">源对象</param>   
  18.         /// <param name="recursionDepth">深度</param>   
  19.         /// <returns>json数据</returns>   
  20.         public static string ToJson(this object obj, int recursionDepth)  
  21.         {  
  22.             JavaScriptSerializer serialize = new JavaScriptSerializer();  
  23.             serialize.RecursionLimit = recursionDepth;  
  24.             return serialize.Serialize(obj);  
  25.         }  
  26.   
  27.         /// <summary>   
  28.         /// DataTable转为json   
  29.         /// </summary>   
  30.         /// <param name="dt">DataTable</param>   
  31.         /// <returns>json数据</returns>   
  32.         public static string ToJson(DataTable dt)  
  33.         {  
  34.             Dictionary<string, object> dic = new Dictionary<string, object>();  
  35.   
  36.             int index = 0;  
  37.             foreach (DataRow dr in dt.Rows)  
  38.             {  
  39.                 Dictionary<string, object> result = new Dictionary<string, object>();  
  40.   
  41.                 foreach (DataColumn dc in dt.Columns)  
  42.                 {  
  43.                     result.Add(dc.ColumnName, dr[dc].ToString());  
  44.                 }  
  45.                 dic.Add(index.ToString(), result);  
  46.                 index++;  
  47.             }  
  48.             return ToJson(dic);  
  49.         }  
  50.     }