当前位置:首页 > C# > 正文

C#中JSON序列化如何忽略空值(详细教程:Newtonsoft.Json与System.Text.Json配置指南)

在使用 C# 进行 Web 开发或 API 接口开发时,经常需要将对象转换为 JSON 字符串。然而,默认情况下,JSON 序列化会包含所有属性,即使它们的值为 null(空值)。这不仅浪费带宽,还可能暴露不必要的数据结构。本文将手把手教你如何在 C# 中配置 JSON 序列化以忽略空值,适用于两种主流库:Newtonsoft.JsonSystem.Text.Json

C#中JSON序列化如何忽略空值(详细教程:Newtonsoft.Json与System.Text.Json配置指南) C# JSON序列化忽略空值  Newtonsoft.Json忽略null System.Text.Json忽略空值 C#序列化配置教程 第1张

为什么需要忽略空值?

假设你有一个用户信息类:

public class User{    public string Name { get; set; }    public string Email { get; set; }    public string PhoneNumber { get; set; } // 可能为空}

如果不做处理,当 PhoneNumbernull 时,序列化结果会是:

{  "Name": "张三",  "Email": "zhangsan@example.com",  "PhoneNumber": null}

而我们希望的结果是:

{  "Name": "张三",  "Email": "zhangsan@example.com"}

这样更简洁、安全且节省流量。下面分别介绍两种主流 JSON 库的配置方法。

方法一:使用 Newtonsoft.Json(Json.NET)忽略空值

Newtonsoft.Json 是 .NET 社区中最流行的 JSON 库之一。要忽略空值,只需设置 NullValueHandling 属性即可。

1. 全局配置(推荐用于 ASP.NET Core)

Program.csStartup.cs 中配置:

// .NET 6+ 的 Program.csusing Newtonsoft.Json.Serialization;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers()    .AddNewtonsoftJson(options =>    {        options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();    });var app = builder.Build();app.MapControllers();app.Run();

2. 单次序列化时忽略空值

using Newtonsoft.Json;var user = new User { Name = "李四", Email = "lisi@example.com" };string json = JsonConvert.SerializeObject(user, Formatting.Indented,    new JsonSerializerSettings    {        NullValueHandling = NullValueHandling.Ignore    });Console.WriteLine(json);

3. 在类或属性上使用特性(Attribute)

[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]public class User{    public string Name { get; set; }    public string Email { get; set; }    public string PhoneNumber { get; set; }}

方法二:使用 System.Text.Json(.NET 内置库)忽略空值

从 .NET Core 3.0 起,微软推出了高性能的内置 JSON 库 System.Text.Json。它同样支持忽略空值。

1. 全局配置(ASP.NET Core)

// Program.cs (.NET 6+)var builder = WebApplication.CreateBuilder(args);builder.Services.ConfigureHttpJsonOptions(options =>{    options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;    options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;});// 如果使用 AddControllers() 而不是 Minimal APIbuilder.Services.AddControllers()    .AddJsonOptions(options =>    {        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;    });var app = builder.Build();app.MapControllers();app.Run();

2. 单次序列化忽略空值

using System.Text.Json;var user = new User { Name = "王五", Email = "wangwu@example.com" };var options = new JsonSerializerOptions{    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,    WriteIndented = true};string json = JsonSerializer.Serialize(user, options);Console.WriteLine(json);

3. 在属性上使用 [JsonIgnore] 特性

注意:这个特性是“始终忽略”,不区分是否为空。如果只想在为空时忽略,请使用全局或单次配置。

public class User{    public string Name { get; set; }    public string Email { get; set; }        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]    public string PhoneNumber { get; set; }}

总结

无论你使用的是 Newtonsoft.Json 还是 System.Text.Json,都可以轻松实现 C# JSON序列化忽略空值 的需求。选择哪种方式取决于你的项目环境:

  • 老项目或需要高级功能 → 用 Newtonsoft.Json
  • 新项目、追求性能 → 用 System.Text.Json

通过本文的 C#序列化配置教程,即使是初学者也能快速上手。记得根据实际需求选择合适的配置方式,让你的 JSON 输出更干净、高效!

如果你觉得这篇关于 Newtonsoft.Json忽略nullSystem.Text.Json忽略空值 的教程有帮助,欢迎收藏或分享给其他开发者!