浅析JSON序列化与反序列化

方法一:引入System.Web.Script.Serialization命名空间使用 JavaScriptSerializer类实现简单的序列化序列化类:Personnel

复制代码 代码如下:


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


执行序列化反序列化:

复制代码 代码如下:


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

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            //执行序列化
            string r1 = jsonSerializer.Serialize(personnel);

            //执行反序列化
            Personnel _Personnel = jsonSerializer.Deserialize<Personnel>(r1);
         }


r1输出结果:{"Id":1,"Name":"小白"}
可以使用 ScriptIgnore属性标记不序列化公共属性或公共字段。

复制代码 代码如下:


        public class Personnel
        {
            [ScriptIgnore]
            public int Id { get; set; }
            public string Name { get; set; }
        }


r1输出结果:{"Name":"小白"}

方法二:引入 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":"小白"}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjgjyf.html