Appearance
Json.NET 序列化与反序列化实践
JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。在 .NET 生态中,Newtonsoft.Json (Json.NET) 是最流行且性能卓越的序列化工具。
1. 基础用法
1.1 序列化与反序列化 DataTable
Json.NET 对 ADO.NET 类型有良好的支持。
csharp
using Newtonsoft.Json;
using System.Data;
// 序列化为 JSON 字符串
string json = JsonConvert.SerializeObject(dt);
// 反序列化回 DataTable
DataTable dtResult = JsonConvert.DeserializeObject<DataTable>(json);1.2 简单对象操作
csharp
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
// 序列化
var employee = new Employee { Name = "Wolfy", Age = 26, Gender = "男" };
string json = JsonConvert.SerializeObject(employee);
// 反序列化
var obj = JsonConvert.DeserializeObject<Employee>(json);2. 序列化控制 (JsonSerializerSettings)
通过 JsonSerializerSettings 可以精细控制序列化行为。
2.1 空值处理 (NullValueHandling)
控制当属性为 null 时是否包含在生成的 JSON 中。
csharp
var jsonSetting = new JsonSerializerSettings();
jsonSetting.NullValueHandling = NullValueHandling.Ignore; // 忽略 null 值
// jsonSetting.NullValueHandling = NullValueHandling.Include; // 包含 null 值 (默认)
string json = JsonConvert.SerializeObject(employee, jsonSetting);2.2 默认值处理 (DefaultValueHandling)
可以配合 [DefaultValue] 特性忽略具有默认值的属性。
csharp
public class Employee
{
[DefaultValue(26)]
public int Age { get; set; }
}
var jsonSetting = new JsonSerializerSettings();
jsonSetting.DefaultValueHandling = DefaultValueHandling.Ignore; // 如果 Age 为 26,则不序列化该字段3. 特性控制 (Attributes)
3.1 成员选择 (OptIn/OptOut)
- OptOut (默认):所有公共成员都会被序列化。使用
[JsonIgnore]排除特定成员。 - OptIn:只有标记了
[JsonProperty]的成员才会被序列化。
csharp
[JsonObject(MemberSerialization.OptIn)]
public class Employee
{
[JsonProperty]
public string Name { get; set; } // 会序列化
public int Age { get; set; } // 不会序列化
}3.2 忽略属性
csharp
public class Employee
{
[JsonIgnore]
public Employee Leader { get; set; } // 永远不会被序列化
}4. 日期处理 (Date Handling)
Json.NET 提供两种主要的日期转换器:
- IsoDateTimeConverter:默认格式,符合 ISO 8601。
- JavaScriptDateTimeConverter:返回 JavaScript
new Date(ticks)格式。
4.1 全局设置
csharp
string json = JsonConvert.SerializeObject(employee, new IsoDateTimeConverter());4.2 特性设置 (针对特定属性)
csharp
public class Employee
{
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime BirthDay { get; set; }
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime EmployeDate { get; set; }
}4.3 自定义日期格式
csharp
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy年MM月dd日" };
string json = JsonConvert.SerializeObject(employee, timeConverter);