JSON序列化與反序列化

方法一:引入System.Web.Script.Serialization命名空間使用 JavaScriptSerializer類實現簡單的序列化
序列化類:Personnel
        publicclass Personnel
         {
            publicint Id { get; set; }
            publicstring Name { get; set; }
         }
執行序列化反序列化:
代碼
        protectedvoid Page_Load(object sender, EventArgs e)
         {
             Personnel personnel = new Personnel();
             personnel.Id = 1;
             personnel.Name = "小白";

             JavaScriptSerializerjsonSerializer = new JavaScriptSerializer();
            //執行序列化
            string r1 =jsonSerializer.Serialize(personnel);
           
            //執行反序列化
             Personnel _Personnel = jsonSerializer.Deserialize<Personnel>(r1);
          }
r1輸出結果:{"Id":1,"Name":"小白"}
可以使用 ScriptIgnore屬性標記不序列化公共屬性或公共字段。
        publicclass Personnel
         {
             [ScriptIgnore]
            publicint Id { get; set; }
            publicstring Name { get; set; }
         }
r1輸出結果:{"Name":"小白"}
方法二:引入 System.Runtime.Serialization.Json命名空間使用 DataContractJsonSerializer類實現序列化
序列化類:People
        publicclass People
         {
            publicint Id { get; set; }
            publicstring Name { get; set; }
         }
執行序列化反序列化 www.aiwalls.com
代碼
        protectedvoid Page_Load(object sender, EventArgs e)
         {
             People people = new People();
             people.Id = 1;
             people.Name = "小白";

             DataContractJsonSerializerjson = new DataContractJsonSerializer(people.GetType());
            string szJson = "";
            //序列化
            using (MemoryStream stream = new MemoryStream())
             {
                 json.WriteObject(stream,people);
                 szJson =Encoding.UTF8.GetString(stream.ToArray());
             }
            //反序列化
            using (MemoryStream ms = newMemoryStream(Encoding.UTF8.GetBytes(szJson)))
             {
                DataContractJsonSerializer serializer = newDataContractJsonSerializer(typeof(People));
                 People _people =(People)serializer.ReadObject(ms);
             }
          }
szJson輸出結果:{"Id":1,"Name":"小白"}
可以使用IgnoreDataMember:指定該成員不是數據協定的一部分且沒有進行序列化,DataMember:定義序列化屬性參數,使用DataMember屬性標記字段必須使用DataContract標記類 否則DataMember標記不起作用。
代碼
         [DataContract]
        publicclass People
         {
             [DataMember(Name = "id")]
            publicint Id { get; set; }
             [IgnoreDataMember]
            publicstring Name { get; set; }
         }
輸出結果: {"id":1}

 

摘自 張毅☆.Net★Java軟件聯盟

發佈留言