答案是使用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 是微软官方提供的高性能 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>可选:格式化输出(带缩进)
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
var options = new JsonSerializerOptions { WriteIndented = true };
string jsonString = JsonSerializer.Serialize(person, options);
如果你使用的是较老的 .NET Framework 项目,或需要更灵活的功能(如支持字段、复杂转换),推荐使用 Newtonsoft.Json。
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")] 自定义输出字段名JsonSerializerOptions.Encoder 或使用 DateTime.ToString("yyyy-MM-dd") 配合自定义转换器基本上就这些。根据你的项目环境选择合适的方式即可。新项目优先用 System.Text.Json,旧项目或需高级功能可选 Newtonsoft.Json。
以上就是C# 怎么将对象序列化为 JSON 字符串_C# 对象序列化 JSON 方法指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号