.NET中JSON資料進行序列化和還原序列化操作分析

來源:互聯網
上載者:User
可以使用DataContractJsonSerializer類將類型執行個體序列化為JSON字串,並將JSON字串還原序列化為類型執行個體。 DataContractJsonSerializer在System.Runtime.Serialization.Json命名空間下

,.NET Framework 3.5包含在System.ServiceModel.Web.dll中,需要添加對其的引用;.NET Framework 4在System.Runtime.Serialization中。

  利用DataContractJsonSerializer序列化和還原序列化的代碼:

 

 1: using System;  2: using System.Collections.Generic;  3: using System.Linq;  4: using System.Web;  5: using System.Runtime.Serialization.Json;  6: using System.IO;  7: using System.Text;  8:  9: /// <summary>  10: /// JSON序列化和還原序列化輔助類  11: /// </summary>  12: public class JsonHelper  13: {  14:     /// <summary>  15:     /// JSON序列化  16:     /// </summary>  17:     public static string JsonSerializer<T>(T t)  18:     {  19:         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));  20:         MemoryStream ms = new MemoryStream();  21:         ser.WriteObject(ms, t);  22:         string jsonString = Encoding.UTF8.GetString(ms.ToArray());  23:         ms.Close();  24:         return jsonString;  25:     }  26:  27:     /// <summary>  28:     /// JSON還原序列化  29:     /// </summary>  30:     public static T JsonDeserialize<T>(string jsonString)  31:     {  32:         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));  33:         MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));  34:         T obj = (T)ser.ReadObject(ms);  35:         return obj;  36:     }  37: }

  序列化Demo:

  簡單對象Person:

1: public class Person  2: {  3:     public string Name { get; set; }  4:     public int Age { get; set; }  5: }

  序列化為JSON字串:

 

 1: protected void Page_Load(object sender, EventArgs e)  2: {  3:     Person p = new Person();  4:     p.Name = "張三";  5:     p.Age = 28;  6:  7:     string jsonString = JsonHelper.JsonSerializer<Person>(p);  8:     Response.Write(jsonString);  9: }

  輸出結果:

 {"Age":28,"Name":"張三"}

  還原序列化Demo:

 1: protected void Page_Load(object sender, EventArgs e)  2: {  3:     string jsonString = "{\"Age\":28,\"Name\":\"張三\"}";  4:     Person p = JsonHelper.JsonDeserialize<Person>(jsonString);  5: }

  ASP.NET中的JSON序列化和還原序列化還可以使用JavaScriptSerializer,在 System.Web.Script.Serializatioin命名空間下,需引用System.Web.Extensions.dll.也可以使用 JSON.NET.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.