当前位置 : 主页 > 网络编程 > net编程 >

c# .net的Newtonsoft.Json序列化和反序列化

来源:互联网 收集:自由互联 发布时间:2023-09-07
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);
}

 

 


网友评论