JSON序列化和反序列化【鸡蛋】

来源:互联网 发布:优化探究 编辑:程序博客网 时间:2024/06/05 17:33

Newtonsoft.Json.dll   下载地址:点击打开链接



using Newtonsoft.Json;using Newtonsoft.Json.Converters;//.net自带的using System.Web.Script.Serialization;namespace JsonData{    public partial class Default : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {         //使用Newtonsoft初始化一个简单对象         Product pro = new Product() { name = "sess", price = 120, fromcity = "city", tocity = "shanghai", intime = DateTime.Now, range = "130cm"};                   string output = JsonConvert.SerializeObject(pro);//序列化对象(将对象转化为json字符串)         Product deserialized = (Product)JsonConvert.DeserializeObject(output, typeof(Product));//反序列化对象(将json字符串转化为对象)         //使用.net自带的JavaScriptSerializer类初始化一个嵌套对象         Product pro1 = new Product() { name = "sess", price = 120, fromcity = "city", tocity = "shanghai", intime = DateTime.Now, range = "130cm", list = new List<car>() { new car() { color = "red", speed = "100KM/h" } } };         //string output1 = JsonConvert.SerializeObject(pro1);//序列化对象(将对象转化为json字符串)         //Product deserialized1 = (Product)JsonConvert.DeserializeObject(output1, typeof(Product));//使用Newtonsoft反序列化对象(将json字符串转化为对象)                 string output2 = new JavaScriptSerializer().Serialize(pro1);//序列化对象(将对象转化为json字符串)         Product deserialized2 = new JavaScriptSerializer().Deserialize<Product>(output2);//反序列化对象(将json字符串转化为对象)        }    }}

    //嵌套实体    public class Product    {        public string name { get; set; }        public int price { get; set; }        public string range { get; set; }        public string fromcity { get; set; }        public string tocity { get; set; }        public DateTime intime { get; set; }        public List<car> list{get;set;}    }    public class car    {      public  string color{get;set;}      public  string speed{get;set;}    }