C#怎么序列化对象为JSON C#使用System.Text.Json进行JSON序列化

来源:这里教程网 时间:2026-02-21 17:30:45 作者:

在C#中,使用 System.Text.Json 命名空间可以方便地将对象序列化为JSON字符串。这是.NET Core 3.0及以上版本内置的高性能JSON库,无需引入第三方依赖。

1. 引入命名空间

要使用 System.Text.Json,首先需要在代码文件顶部添加引用:

using System.Text.Json;
using System.Text.Json.Serialization;

2. 定义要序列化的类

创建一个普通的C#类,例如表示用户信息:

public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}

3. 序列化对象为JSON字符串

使用 JsonSerializer.Serialize() 方法将对象转换为JSON:

var user = new User
{
Id = 1,
Name = "张三",
Email = "zhangsan@example.com"
};

string json = JsonSerializer.Serialize(user);
Console.WriteLine(json);
// 输出: {"Id":1,"Name":"张三","Email":"zhangsan@example.com"}

4. 格式化输出(美化JSON)

如果希望输出的JSON带缩进、更易读,可以配置序列化选项:

var options = new JsonSerializerOptions
{
WriteIndented = true
};

string prettyJson = JsonSerializer.Serialize(user, options);
Console.WriteLine(prettyJson);
// 输出带换行和缩进的JSON

5. 控制序列化行为

可以通过属性特性来控制哪些字段参与序列化,或修改字段名称:

public class User
{
[JsonPropertyName("user_id")]
public int Id { get; set; }

[JsonIgnore]
public string Email { get; set; } // 不参与序列化

public string Name { get; set; }
}

这样序列化后,Id会变成"user_id",Email字段则被忽略。

6. 处理复杂类型或集合

序列化列表也很简单:

var users = new List
{
new User { Id = 1, Name = "张三" },
new User { Id = 2, Name = "李四" }
};

string json = JsonSerializer.Serialize(users, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);
基本上就这些。System.Text.Json 使用起来直接,性能好,适合大多数JSON序列化场景。注意确保对象的属性有公共的getter/setter,否则可能无法正确序列化。

相关推荐