C# 解析复杂的Json格式_修改解析后的Json(序列化,反序列化)

2019-08-22  更新  添加注意事项

以下是Model实例源码    注意:下面每个字段都是public 不然解析是空 2019-08-22
    public class PersonInfo_Model
    {   //转发请保留原创地址 http://www.luofenming.com/show.aspx?id=ART2018081400001
        public int errorcode { get; set; }
        public string message { get; set; }
        public Data_Model data { get; set; }
    }
    public class Data_Model
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
        public int sex { get; set; }
        public Address_Model address { get; set; }
    }

    public class Address_Model
    {
        public string name { get; set; }
        public string postcode { get; set; }
    }
以下是解析与修改Json//引用程序集System.Web.Extensions
using System.Web.Script.Serialization;
        private void button1_Click(object sender, EventArgs e)
        {
            string rJson = "{\r\n                \"errorcode\":0,\r\n	\"message\":\"\",\r\n	\"data\":{\r\n                    \"id\":1,		\"name\":\"罗分明\",\r\n		\"age\":23,\r\n		\"sex\":0,\r\n		\"address\":{\r\n                        \"name\":\"江西九江\",\r\n			\"postcode\":\"4111003\"\r\n        }\r\n                }\r\n}"; 

            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            javaScriptSerializer.MaxJsonLength = Int32.MaxValue;
            //反序列化Json成PersonInfo_Model  注意PersonInfo_Model所有的字段要跟Json里成的  KEY对应 不然反序列后会成空
            PersonInfo_Model dataModel = javaScriptSerializer.Deserialize<PersonInfo_Model>(rJson);
            
            string name = dataModel.data.address.name;//这样可以获得  "江西九江"
            dataModel.data.address.name = "广东珠海";

            string s= javaScriptSerializer.Serialize(dataModel);//将Model序列化成string
        }

评论