JavaScriptSerializer实现JSON序列化与反序列化的简单例子

1.JSON序列化

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Script.Serialization;



namespace test2

{

    public partial class WebForm6 : System.Web.UI.Page

    {

        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();

            //执行序列化

            lgx.Text = jsonSerializer.Serialize(personnel);

            //输出结果:{"Id":1,"Name":"小白"}

        }

    }

}

可以使用 ScriptIgnore属性标记不序列化公共属性或公共字段。

        public class Personnel

        {

            [ScriptIgnore]

            public int Id { get; set; }

            public string Name { get; set; }

        }

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

2.JSON反序列化

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Script.Serialization;



namespace test2

{

    public partial class WebForm6 : System.Web.UI.Page

    {

        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 it = jsonSerializer.Serialize(personnel);

            //输出结果:{"Id":1,"Name":"小白"}

            Personnel _personnel = jsonSerializer.Deserialize<Personnel>(it);

            lgx.Text = "id" + _personnel.Id.ToString() + "Name" + _personnel.Name;

        }

    }

}

 

你可能感兴趣的:(JavaScript)