以下是一些 System.Text.Json 在 .NET 9.0 中的使用方式,包括序列化、反序列化、配置选项等,并附上输出结果。
- 基本序列化和反序列化
cs
using System;
using System.Text.Json;
public class Program
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void Main()
{
Person person = new Person { Name = "张三", Age = 30 };
// 序列化
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine("序列化结果:");
Console.WriteLine(jsonString);
// 反序列化
Person deserializedPerson = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine("\n反序列化结果:");
Console.WriteLine($"姓名:{deserializedPerson.Name}, 年龄:{deserializedPerson.Age}");
}
}
- 输出结果:
cs
序列化结果:
{"Name":"张三","Age":30}
反序列化结果:
姓名:张三, 年龄:30
- 使用配置选项
cs
using System;
using System.Text.Json;
public class Program
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void Main()
{
Person person = new Person { Name = "张三", Age = 30 };
// 配置选项
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
// 序列化
string jsonString = JsonSerializer.Serialize(person, options);
Console.WriteLine("序列化结果(使用配置选项):");
Console.WriteLine(jsonString);
}
}
输出结果:
cs
序列化结果(使用配置选项):
{
"name": "张三",
"age": 30
}
- 处理嵌套对象
cs
using System;
using System.Text.Json;
public class Program
{
public class Address
{
public string City { get; set; }
public string Street { get; set; }
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
}
public static void Main()
{
Person person = new Person
{
Name = "张三",
Age = 30,
Address = new Address { City = "北京", Street = "长安街" }
};
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine("序列化结果(嵌套对象):");
Console.WriteLine(jsonString);
}
}
输出结果:
cs
序列化结果(嵌套对象):
{"Name":"张三","Age":30,"Address":{"City":"北京","Street":"长安街"}}
- 处理集合
cs
using System;
using System.Collections.Generic;
using System.Text.Json;
public class Program
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void Main()
{
List<Person> people = new List<Person>
{
new Person { Name = "张三", Age = 30 },
new Person { Name = "李四", Age = 25 }
};
string jsonString = JsonSerializer.Serialize(people);
Console.WriteLine("序列化结果(集合):");
Console.WriteLine(jsonString);
}
}
输出结果:
cs
序列化结果(集合):
[{"Name":"张三","Age":30},{"Name":"李四","Age":25}]