标签:get console 关键字 round java ddr 包含 属性 异常
关键字:【序列化】【反序列化】【Json】【Newtonsoft.Json】
调用无参构造函数,new出一个实例,然后使用Json字符串中包含的字段or属性为成员赋值,Json字符串未提供的字段or属性的值是无参构造函数初始化的值或是0,false,null;若类未提供无参构造函数,则调用有参构造函数,但是要保证类仅有一个有参构造函数,多个有参构造函数时,若不指定哪个构造函数来反序列化,编译器会报错。所以,尽可能的为会进行序列化和反序列化的类提供无参构造函数。
class Person { private string name; public string Name { get => name; set => name = value; } //年龄 private int age; public int Age { get => age; set => age = value; } //城市 public string City { get; set; } //技能 public List<string> languages; public Person() { Name = "Andrew Magic"; Age = 20; City = "Zhuhai"; languages = new List<string>(); } }
Person p1 = new Person(); string p1JsonStr = JsonConvert.SerializeObject(p1);
string p2JsonStr = "{\"Name\":\"Jack\" }"; Person p2 = JsonConvert.DeserializeObject<Person>(p2JsonStr);
Person p3 = new Person(); p3.Name = "LiMing"; p3.Age = 22; p3.City = "Shanghai"; p3.languages.AddRange(new string[] { "C", "Java", "PHP" }); Person p4 = new Person(); p4.Name = "ZhangSan"; p4.Age = 20; p4.City = "Beijing"; p4.languages.AddRange(new string[] { "C#", "Python", "Go" }); List<Person> list = new List<Person> { p3, p4 }; string objectsJsonStr = JsonConvert.SerializeObject(list);
List<Person> list = JsonConvert.DeserializeObject<List<Person>>(objectsJsonStr); foreach (Person item in list) { Console.WriteLine(item.Name); }
标签:get console 关键字 round java ddr 包含 属性 异常
原文地址:https://www.cnblogs.com/liweiaila/p/10360666.html