這篇文章主要介紹了C#實現的json序列化和反序列化代碼實例,本文講解了兩種實現方法,並直接給出代碼示例,需要的朋友可以參考下
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 using System; using System.Collections.Generic; using System.Web.Script.Serialization; using System.Configuration; using System.Runtime.Serialization.Json; using System.Runtime.Serialization; using System.IO; using System.Text; namespace WebApplication1 { //方法一:引入System.Web.Script.Serialization命名空間使用 JavaScriptSerializer類實現簡單的序列化 [Serializable] public class Person { private int id; /// <summary> /// id /// </summary> public int Id { get { return id; } set { id = value; } } private string name; /// <summary> /// 姓名 /// </summary> public string Name { get { return name; } set { name = value; } } } //方法二:引入 System.Runtime.Serialization.Json命名空間使用 DataContractJsonSerializer類實現序列化 //可以使用IgnoreDataMember:指定該成員不是數據協定的一部分且沒有進行序列化,DataMember:定義序列化屬性參數,使用DataMember屬性標記字段必須使用DataContract標記類 否則DataMember標記不起作用。 [DataContract] public class Person1 { [IgnoreDataMember] public int Id { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "sex")] public string Sex { get; set; } } public partial class _Default : System.Web.UI.Page { string constr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { Person p1 = new Person(); p1.Id = 1; p1.Name = "dxw"; Person p2 = new Person(); p2.Id = 2; p2.Name = "wn"; List<Person> listperson = new List<Person>(); listperson.Add(p1); listperson.Add(p2); JavaScriptSerializer js = new JavaScriptSerializer(); //json序列化 string s = js.Serialize(listperson); Response.Write(s); //方法二 Person1 p11 = new Person1(); p11.Id = 1; p11.Name = "hello"; p11.Sex = "男"; DataContractJsonSerializer json = new DataContractJsonSerializer(p11.GetType()); string szJson = ""; //序列化 using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, p11); szJson = Encoding.UTF8.GetString(stream.ToArray()); Response.Write(szJson); } //反序列化 //using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) //{ // DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People)); // Person1 _people = (Person1)serializer.ReadObject(ms); //} } protected void Button1_Click(object sender, EventArgs e) { Response.Write(constr); } }