Json序列化与反序列化

 1:序列化类,需要引用命名空间:System.ServerModel.Web 和System.Runtime.Serialization

 public class JOSNHelper
    {
        public static string GetJosn<T>(T obj)
        {
            DataContractJsonSerializer josn = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms=new MemoryStream())
            {
                josn.WriteObject(ms,obj);
                string szJson = Encoding.UTF8.GetString(ms.ToArray());
                return szJson;
            }
        }

        public static T ParseFormJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
                return (T)dcj.ReadObject(ms);
            }
        }
    }

2:实例化的类

public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
    }

3:使用json

 public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Person p1 = new Person() { Id=1, Name="男", Sex="女" };
            string mystr=JOSNHelper.GetJosn<Person>(p1);
            Label1.Text = mystr;
        }

        protected void btn1_Click(object sender, EventArgs e)
        {
            Person pa = JOSNHelper.ParseFormJson<Person>(Label1.Text);
            Label1.Text = pa.Name;
        }
    }

 

posted @ 2012-09-25 14:24  王永华  阅读(110)  评论(0编辑  收藏  举报