信息发布→ 登录 注册 退出

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

发布时间:2025-11-15

点击量:
答案是使用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} } }

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

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

标签:# 对象  # 序列化  # 如果你  # 李四  # 更灵活  # 安装包  # 的是  # 高性能  # 可选  # 自定义  # 推荐使用  # js  # using  # 字符串  # 命名空间  # yy  # .net  # 格式化输出  # c#  # 微软  # ai  # json  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!