答案是使用System.Text.Json或Newtonsoft.Json将对象序列化为JSON字符串。首先介绍System.Text.Json,它是.NET Core 3.0+内置的高性能库,通过JsonSerializer.Serialize方法实现序列化,支持格式化输出和忽略空值等选项;然后介绍Newtonsoft.Json,适用于旧项目或需要更灵活功能的情况,通过JsonConvert.SerializeObject方法实现,并支持字段、命名控制和日期格式化等高级特性。新项目推荐使用System.Text.Json,旧项目可选用Newtonsoft.Json。

在 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;public class Person { public string Name { get; set; } public int Age { get; set; } }
class Program { static void Main() { var person = new Person { Name = "张三", Age = 25 }; string jsonString = JsonSerializer.Serialize(person); Console.WriteLine(jsonString); // 输出: {"Name":"张三","Age":25} } }
可选:格式化输出(带缩进)
本文档主要讲述的是JSON.NET 简单的使用;JSON.NET使用来将.NET中的对象转换为JSON字符串(序列化),或者将JSON字符串转换为.NET中已有类型的对象(反序列化?)。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
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;public class Person { public string Name { get; set; } public int Age { get; set; } }
class Program { static void Main() { var person = new Person { Name = "李四", Age = 30 }; string jsonString = JsonConvert.SerializeObject(person); Console.WriteLine(jsonString); // 输出: {"Name":"李四","Age":30}
// 格式化输出 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。









