// 简单对象定义
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
// 序列化
var product = new Product { Id = 1, Name = "Laptop", Price = 999.99m };
string json = JsonSerializer.Serialize(product);
// 反序列化
Product deserialized = JsonSerializer.Deserialize<Product>(json);
2.2 流式处理大文件
// 写入大型JSON
await using (var fs = File.Create("bigfile.json"))
{
await JsonSerializer.SerializeAsync(fs, largeData);
}
// 读取大型JSON
await using (var fs = File.OpenRead("bigfile.json"))
{
var data = await JsonSerializer.DeserializeAsync<BigData>(fs);
}
三、高级配置与自定义
3.1 JsonSerializerOptions详解
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 命名策略
WriteInde