欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-15 20:26: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 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);
}

 

 

相关标签: c#