C#中Json序列化与反序列化

xiaoxiao2021-03-01  40

using Newtonsoft.Json; using System; using System.IO; using System.Runtime.Serialization.Json; using System.Text; using System.Web.Script.Serialization; namespace TestSerializable_json { [Serializable] public class Person { public int Id { get; set; } public string Name { get; set; } public Person() { } public Person(int id,string name) { this.Id = id; this.Name = name; } } class Program { static void Main(string[] args) { JavaScriptSerializer(); DataContractJsonSerializer(); JsonNet(); Console.ReadLine(); } /// <summary> /// 使用JavaScriptSerializer类需要引用System.Web.Script.Serialization,添加引用System.Web.Extensions /// </summary> public static void JavaScriptSerializer() { //序列化 Person person = new Person(6, "Mond"); JavaScriptSerializer js = new JavaScriptSerializer(); string jsonStr = js.Serialize(person); //反序列化 Person person1 = js.Deserialize<Person>(jsonStr); Console.WriteLine(person1.Id + "\n" + person.Name); } /// <summary> /// 使用DataContractJsonSerializer需要引用System.Runtime.Serialization.Json /// </summary> public static void DataContractJsonSerializer() { //序列化 Person person = new Person(6, "Mond"); DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Person)); MemoryStream stream = new MemoryStream(); js.WriteObject(stream, person); stream.Position = 0; StreamReader sr = new StreamReader(stream, Encoding.UTF8); string json = sr.ReadToEnd(); sr.Close(); stream.Close(); //反序列化 var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Person)); Person person1 = (Person)deserializer.ReadObject(ms); Console.WriteLine(person1.Id + "\n" + person1.Name); } /// <summary> /// 使用json.net需要在NuGut程序包中引入类库json.net,代码开头引用Newtonsoft.Json /// </summary> public static void JsonNet() { //序列化 Person person = new Person(6,"Mond"); string jsonStr = JsonConvert.SerializeObject(person); //反序列化 Person person1 = (Person)JsonConvert.DeserializeObject<Person>(jsonStr); Console.WriteLine(person1.Id + "\n" + person1.Name); } } }

 

转载请注明原文地址: https://www.6miu.com/read-4200197.html

最新回复(0)