在使用 C# 进行开发时,我们经常需要将对象转换为 JSON 字符串(即 JSON 序列化)。但有时,并非对象的所有属性都需要被序列化到 JSON 中。例如,出于安全考虑(如密码字段)、性能优化或 API 设计规范等原因,我们需要在序列化过程中忽略某些属性。
本文将详细介绍在 C# 中如何通过两种主流的 JSON 库——Newtonsoft.Json(也称 Json.NET)和 .NET 内置的 System.Text.Json——来实现“忽略指定属性”的功能。无论你是刚入门的新手,还是有一定经验的开发者,都能轻松掌握这些技巧。
Newtonsoft.Json 是 .NET 社区中最流行的 JSON 处理库之一。它提供了非常灵活的注解方式来控制序列化行为。
要忽略某个属性,只需在该属性上添加 [JsonIgnore] 特性即可。
using Newtonsoft.Json;public class User{ public string Name { get; set; } public string Email { get; set; } [JsonIgnore] public string Password { get; set; }}// 使用示例var user = new User{ Name = "张三", Email = "zhangsan@example.com", Password = "123456"};string json = JsonConvert.SerializeObject(user);Console.WriteLine(json);// 输出:{"Name":"张三","Email":"zhangsan@example.com"} 如上所示,Password 属性被成功忽略,不会出现在最终的 JSON 字符串中。
从 .NET Core 3.0 开始,微软推出了自己的高性能 JSON 库 System.Text.Json。它的用法与 Newtonsoft.Json 类似,但命名空间不同。
同样,使用 [JsonIgnore] 特性,但需引用 System.Text.Json.Serialization 命名空间。
using System.Text.Json;using System.Text.Json.Serialization;public class User{ public string Name { get; set; } public string Email { get; set; } [JsonIgnore] public string Password { get; set; }}// 使用示例var user = new User{ Name = "李四", Email = "lisi@example.com", Password = "abcdef"};string json = JsonSerializer.Serialize(user);Console.WriteLine(json);// 输出:{"Name":"李四","Email":"lisi@example.com"} [JsonIgnore] 可能无法识别。ShouldSerialize 方法或自定义 ContractResolver,而 System.Text.Json 则可通过自定义 JsonConverter 实现。无论是使用 Newtonsoft.Json 还是 System.Text.Json,在 C# 中忽略 JSON 序列化的指定属性都非常简单。只需在目标属性上添加 [JsonIgnore] 特性即可。
掌握这一技巧,不仅能提升你的 API 安全性,还能让你的 JSON 输出更加干净、符合业务需求。希望这篇关于 C# JSON序列化 的教程对你有所帮助!
如果你正在学习 忽略属性 的相关知识,不妨动手尝试一下上面的代码示例。实践是掌握 Newtonsoft.Json 和 System.Text.Json 最好的方式!
本文由主机测评网于2025-12-15发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/2025128105.html