C# 怎么将对象序列化为 JSON 字符串_C# 对象序列化 JSON 方法指南

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

在 C# 中将对象序列化为 JSON 字符串,最常用的方法是使用 System.Text.Json 或第三方库如 Newtonsoft.Json(又称 Json.NET)。以下是两种主流方式的详细说明和示例。

使用 System.Text.Json(.NET Core 3.0+ 推荐)

System.Text.Json 是微软官方提供的高性能 JSON 操作库,内置在 .NET Core 3.0 及以上版本中,无需额外安装包。

基本用法:

引入命名空间:
using System.Text.Json;
调用
JsonSerializer.Serialize()
方法将对象转为 JSON 字符串

示例代码:

using System;
using System.Text.Json;
<p>public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}</p><p>class Program
{
static void Main()
{
var person = new Person { Name = "张三", Age = 25 };
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine(jsonString); // 输出: {"Name":"张三","Age":25}
}
}</p>

可选:格式化输出(带缩进)

var options = new JsonSerializerOptions { WriteIndented = true };
string jsonString = JsonSerializer.Serialize(person, options);

使用 Newtonsoft.Json(兼容性更强)

如果你使用的是较老的 .NET Framework 项目,或需要更灵活的功能(如支持字段、复杂转换),推荐使用 Newtonsoft.Json

通过 NuGet 安装包:
Install-Package Newtonsoft.Json
引入命名空间:
using Newtonsoft.Json;
使用
JsonConvert.SerializeObject()
方法

示例代码:

using System;
using Newtonsoft.Json;
<p>public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}</p><p>class Program
{
static void Main()
{
var person = new Person { Name = "李四", Age = 30 };
string jsonString = JsonConvert.SerializeObject(person);
Console.WriteLine(jsonString); // 输出: {"Name":"李四","Age":30}</p><pre class='brush:php;toolbar:false;'>    // 格式化输出
    string prettyJson = JsonConvert.SerializeObject(person, Formatting.Indented);
    Console.WriteLine(prettyJson);
}

}

处理常见场景的建议

忽略空值属性: 使用
JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
(System.Text.Json)
属性命名控制: 使用
[JsonPropertyName("name")]
[JsonProperty("name")]
自定义输出字段名
私有成员/字段支持: Newtonsoft.Json 支持更广,可通过特性配置序列化非公共成员 日期格式化: 可设置
JsonSerializerOptions.Encoder
或使用
DateTime.ToString("yyyy-MM-dd")
配合自定义转换器

基本上就这些。根据你的项目环境选择合适的方式即可。新项目优先用 System.Text.Json,旧项目或需高级功能可选 Newtonsoft.Json

相关推荐