Newtonsoft.Json 序列化属性详解:控制JSON序列化的艺术
前言
在现代.NET开发中,JSON序列化是系统间数据交换的核心技术。Newtonsoft.Json作为.NET生态中最流行的JSON处理库,提供了丰富的特性来控制序列化过程。其中,序列化属性(Serialization Attributes)是最常用且强大的功能之一,它允许开发者精细控制对象如何被转换为JSON以及如何从JSON重建对象。
标准.NET序列化属性与Newtonsoft.Json
Newtonsoft.Json不仅支持自身的专有属性,还能识别标准的.NET序列化属性:
SerializableAttribute
:标记可序列化的类DataContractAttribute
/DataMemberAttribute
:WCF风格的序列化控制NonSerializedAttribute
:标记不应序列化的字段
重要提示:当Newtonsoft.Json属性与标准.NET属性同时存在时,Newtonsoft.Json属性具有更高优先级。例如,如果同时使用JsonPropertyAttribute
和DataMemberAttribute
指定属性名,将采用JsonPropertyAttribute
的命名。
Newtonsoft.Json核心序列化属性详解
1. JsonObjectAttribute:类级别的序列化控制
JsonObjectAttribute
用于控制整个类的序列化行为:
- MemberSerialization:指定成员序列化模式
- OptIn:只有显式标记的成员才会被序列化
- OptOut:默认模式,所有公共成员都会被序列化(除非显式忽略)
- Fields:序列化所有字段(包括私有字段),忽略属性
[JsonObject(MemberSerialization.OptIn)]
public class User
{
[JsonProperty] // 只有标记的才会被序列化
public string Name { get; set; }
public int Age { get; set; } // 不会被序列化
}
- NamingStrategy:可设置命名策略,如驼峰式、蛇形命名等
- 对于实现了IEnumerable的类,默认会序列化为JSON数组,使用此属性可强制序列化为对象
2. JsonArrayAttribute/JsonDictionaryAttribute:集合类型控制
这两个属性专门用于集合类型:
JsonArrayAttribute
:明确指定类应序列化为JSON数组JsonDictionaryAttribute
:明确指定类应序列化为JSON对象(字典)
[JsonDictionary(NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class CustomDictionary : Dictionary<string, string>
{
// 会使用蛇形命名法序列化键名
}
3. JsonPropertyAttribute:属性级精细控制
这是最常用的属性,功能丰富:
- 自定义属性名:允许JSON属性名与.NET属性名不同
- 控制可见性:可序列化非公共属性
- 空值处理:自定义null值的处理方式
- 默认值:设置默认值行为
- 类型处理:控制类型名称和引用处理
- 命名策略:为单个属性设置命名策略
public class Product
{
[JsonProperty("product_name")] // 自定义JSON属性名
public string Name { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public decimal Price { get; set; }
}
4. JsonIgnoreAttribute:排除序列化
简单直接地排除字段或属性:
public class Account
{
public string Username { get; set; }
[JsonIgnore] // 密码不会被序列化
public string Password { get; set; }
}
5. JsonConverterAttribute:自定义转换逻辑
允许为类或属性指定自定义转换器:
[JsonConverter(typeof(CustomDateTimeConverter))]
public class Event
{
public DateTime Date { get; set; }
}
// 或者在属性级别应用
public class LogEntry
{
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime Timestamp { get; set; }
}
6. JsonExtensionDataAttribute:处理额外数据
用于捕获JSON中不存在于类定义中的额外属性:
public class Person
{
public string Name { get; set; }
[JsonExtensionData]
public IDictionary<string, JToken> AdditionalData { get; set; }
}
7. JsonConstructorAttribute:自定义构造逻辑
指定反序列化时应使用的构造函数:
public class Rectangle
{
public int Width { get; }
public int Height { get; }
[JsonConstructor]
public Rectangle(int width, int height)
{
Width = width;
Height = height;
}
}
最佳实践与性能考虑
- 属性选择:优先使用Newtonsoft.Json专有属性,它们提供更丰富的功能
- 命名策略:在API设计中保持一致的命名约定
- 性能优化:
- 对于频繁序列化的类型,考虑使用
JsonConverterAttribute
- 避免在热路径上使用复杂的自定义转换器
- 对于频繁序列化的类型,考虑使用
- 安全性:
- 敏感数据务必使用
JsonIgnore
- 谨慎使用
JsonExtensionData
,防止意外数据注入
- 敏感数据务必使用
总结
Newtonsoft.Json的序列化属性提供了强大的工具集,让开发者能够精确控制对象与JSON之间的转换过程。理解并合理运用这些属性,可以解决大多数序列化场景中的特殊需求,同时保证代码的清晰性和可维护性。无论是简单的DTO还是复杂的领域模型,这些属性都能帮助你实现理想的序列化结果。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考