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 Liststring langu
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);
}