JSON的序列化和反序列化已经成为WEB开发不可缺少的知识。
什么是JSON?
JSON(JavaScript Object Notation) is a lightweight data-interchange format.It is easy for humans to read and write and easy for machines to parse and generate.JSON is a text format that is completely language independent.
JSON(JavaScript对象标记法)是一种轻量级数据交换格式。它便于我们读写,也便于计算机生成与解析。JSON是一种完全独立于语言的文本格式。
C#中序列化与反序列化的方式主要有
JavaScriptSerializer(System.Web.Extensions System.Web.Script.Serialization)
JsonConvert(Json.NET Newtonsoft.Json)
下面分别举例说明两种方法的使用。
创建一个Person类
1 class Person 2 { 3 public string Name { get; set; } 4 public int Age { get; set; } 5 public Dictionary<string, object> WorkExperience { get; set; } 6 public Person() { } 7 public void Say(){ } 8 }
实例化Person
1 var person = new Person(); 2 person.Name = "张三"; 3 person.Age = 27; 4 person.WorkExperience = new Dictionary<string, object>(); 5 person.WorkExperience.Add("A公司", "A职位"); 6 person.WorkExperience.Add("B公司", "B职位");
JsonConvert Demo
1 var serializeObject1 = JsonConvert.SerializeObject(person); 2 var deserializeObject1 = JsonConvert.DeserializeObject(serializeObject1); 3 Console.WriteLine("使用JsonConvert序列化与反序列化"); 4 Console.WriteLine("序列化结果"); 5 Console.WriteLine(serializeObject1); 6 Console.WriteLine("反序列化结果"); 7 Console.WriteLine(deserializeObject1); 8 Console.WriteLine();
JavaScriptSerializer Demo
1 var serializeObject2 = new JavaScriptSerializer().Serialize(person); 2 var deserializeObject2 = new JavaScriptSerializer().Deserialize<Person>(serializeObject2); 3 Console.WriteLine("使用JavaScriptSerializer序列化与反序列化"); 4 Console.WriteLine("序列化结果"); 5 Console.WriteLine(serializeObject2); 6 Console.WriteLine("反序列化结果"); 7 Console.WriteLine(deserializeObject2); 8 Console.WriteLine("姓名:{0},年龄:{1}".FormatWith(deserializeObject2.Name, deserializeObject2.Age));
好记性不如烂笔头,每天学习点,每天分享点,不忘初心...