在使用 C# 进行 Web 开发或 API 接口开发时,经常需要将对象转换为 JSON 字符串。然而,默认情况下,JSON 序列化会包含所有属性,即使它们的值为 null(空值)。这不仅浪费带宽,还可能暴露不必要的数据结构。本文将手把手教你如何在 C# 中配置 JSON 序列化以忽略空值,适用于两种主流库:Newtonsoft.Json 和 System.Text.Json。
假设你有一个用户信息类:
public class User{ public string Name { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } // 可能为空} 如果不做处理,当 PhoneNumber 为 null 时,序列化结果会是:
{ "Name": "张三", "Email": "zhangsan@example.com", "PhoneNumber": null} 而我们希望的结果是:
{ "Name": "张三", "Email": "zhangsan@example.com"} 这样更简洁、安全且节省流量。下面分别介绍两种主流 JSON 库的配置方法。
Newtonsoft.Json 是 .NET 社区中最流行的 JSON 库之一。要忽略空值,只需设置 NullValueHandling 属性即可。
在 Program.cs 或 Startup.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(); 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); [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]public class User{ public string Name { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; }} 从 .NET Core 3.0 起,微软推出了高性能的内置 JSON 库 System.Text.Json。它同样支持忽略空值。
// 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(); 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); 注意:这个特性是“始终忽略”,不区分是否为空。如果只想在为空时忽略,请使用全局或单次配置。
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序列化忽略空值 的需求。选择哪种方式取决于你的项目环境:
通过本文的 C#序列化配置教程,即使是初学者也能快速上手。记得根据实际需求选择合适的配置方式,让你的 JSON 输出更干净、高效!
如果你觉得这篇关于 Newtonsoft.Json忽略null 和 System.Text.Json忽略空值 的教程有帮助,欢迎收藏或分享给其他开发者!
本文由主机测评网于2025-12-08发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/2025124700.html