C#通用Json格式序列化和還原序列化的方法

來源:互聯網
上載者:User

引入 System.Runtime.Serialization.Json命名空間使用 DataContractJsonSerializer類實現序列化

序列化類別:People

        public class People
{
public int Id { get; set; }
public string Name { get; set; }
}

執行序列化還原序列化

        protected void Page_Load(object sender, EventArgs e)
{
People people = new People();
people.Id = 1;
people.Name = "小白";


DataContractJsonSerializer json = new DataContractJsonSerializer(people.GetType());
string szJson = "";
//序列化
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, people);
szJson = Encoding.UTF8.GetString(stream.ToArray());
}
//還原序列化
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
People _people = (People)serializer.ReadObject(ms);
}
}

szJson輸出結果:{"Id":1,"Name":"小白"}

可以使用IgnoreDataMember:指定該成員不是資料合約的一部分且沒有進行序列化,DataMember:定義序列化屬性參數,使用DataMember屬性標記欄位必須使用DataContract標記類
否則DataMember標記不起作用。

        [DataContract]
public class People
{
[DataMember(Name = "id")]
public int Id { get; set; }
[IgnoreDataMember]
public string Name { get; set; }
}

輸出結果: {"id":1}

 

 

 

進行簡單封裝一下

 

using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace RRQ.Common
{
    public static class JsonExtension
    {
        /// <summary>
        /// 序列化Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <returns></returns>
        public static string JsonSerialize<T>(this object target)
        {
            T result = (T)target;

            DataContractJsonSerializer json = new DataContractJsonSerializer(result.GetType());

            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, result);
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        /// <summary>
        /// 返序列化Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(this string target)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(target)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }
    }
}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.