.NET 9 中 System.Text.Json 庫的全面升級與實踐指南
在 .NET 9 中,System.Text.Json 庫得到了顯著增強,為開發(fā)者提供了更強大和靈活的 JSON 處理能力。這些改進主要集中在 JSON 架構(gòu)支持、智能應用功能以及序列化和反序列化過程的自定義選項上。本文將詳細介紹這些新特性,并提供示例代碼,幫助開發(fā)者更好地理解和應用這些功能。
JSON 架構(gòu)導出器
在 .NET 9 中,新增了 JsonSchemaExporter 類,使開發(fā)者能夠從 .NET 類型中提取 JSON 架構(gòu)文檔。這一特性有助于驗證和文檔化 JSON 數(shù)據(jù)結(jié)構(gòu),確保應用程序之間的一致性。
示例代碼
using System.Text.Json;
using System.Text.Json.Schema;
namespace AppTextJson
{
publicclass Employee
{
publicint Id { get; set; }
publicstring Name { get; set; }
publicstring Position { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
var options = new JsonSerializerOptions
{
WriteIndented = true
};
string jsonSchema = JsonSerializer.Serialize(new Employee(), options);
Console.WriteLine(jsonSchema);
Console.ReadKey();
}
}
}
輸出示例
圖片
可空引用類型支持
為了與 C# 的可空引用類型注釋保持一致,System.Text.Json 現(xiàn)在提供了 RespectNullableAnnotations 選項。當啟用時,序列化和反序列化過程中會強制執(zhí)行不可空引用類型,若不可空屬性被賦值為 null,則會拋出異常。
示例代碼
using System.Text.Json;
using System.Text.Json.Schema;
using System.Text.Json.Serialization;
namespace AppTextJson
{
publicclass Product
{
publicstring Name { get; set; } = null!;
public decimal Price { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
var options = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
var product = new Product { Name = null, Price = 9.99m };
string json = JsonSerializer.Serialize(product, options);
Console.WriteLine(json);
Console.ReadKey();
}
}
}
輸出示例
圖片
自定義序列化縮進
System.Text.Json 引入了自定義縮進選項,允許開發(fā)者指定用于縮進的字符和大小,以滿足特定的格式要求。這有助于使 JSON 輸出更易讀。
示例代碼
var options = new JsonSerializerOptions
{
WriteIndented = true
};
var json = JsonSerializer.Serialize(new { Name = "Alice", Age = 30 }, options);
Console.WriteLine(json);
輸出示例
圖片
JsonSerializerOptions.Web
JsonSerializerOptions.Web 提供了一組預定義的選項,專為 Web 應用程序量身定制。這包括屬性名稱的 camelCase 格式和靈活的數(shù)字處理,使 JSON 序列化符合常見的 Web API 實踐。
示例代碼
internal class Program
{
static void Main(string[] args)
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var json = JsonSerializer.Serialize(new { FirstName = "John", LastName = "Doe" }, options);
Console.WriteLine(json);
Console.ReadKey();
}
}
輸出示例
圖片
JsonObject 屬性排序
JsonObject 類現(xiàn)在允許開發(fā)者控制 JSON 對象中屬性的順序。這在某些序列化場景中尤其有用,或者在與對屬性順序敏感的系統(tǒng)交互時。
示例代碼
internal class Program
{
static void Main(string[] args)
{
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var json = JsonSerializer.Serialize(new { LastName = "Doe", FirstName = "John" }, options);
Console.WriteLine(json);
Console.ReadKey();
}
}
輸出示例
圖片
JsonElement 深度比較方法
在 .NET 9 中,System.Text.Json 庫引入了 JsonElement.DeepEquals 方法,使得兩個 JsonElement 實例之間的深度比較變得更加簡單。該方法可以判斷兩個 JSON 元素在結(jié)構(gòu)和語義上是否相同。
示例代碼
internal class Program
{
static void Main(string[] args)
{
var json1 = JsonDocument.Parse("{\"name\":\"Alice\"}").RootElement;
var json2 = JsonDocument.Parse("{\"name\":\"Alice\"}").RootElement;
Console.WriteLine(JsonElement.DeepEquals(json1, json2));
Console.ReadKey();
}
}
輸出示例
圖片
自定義枚舉成員名稱
在 .NET 9 中,System.Text.Json 庫引入了 JsonStringEnumMemberName 屬性,允許開發(fā)者自定義單個枚舉成員的 JSON 表示。這一增強提供了更大的靈活性,尤其是在需要特定命名約定或格式的場景中。
示例代碼
using System.Text.Json;
using System.Text.Json.Schema;
using System.Text.Json.Serialization;
namespace AppTextJson
{
[JsonConverter(typeof(JsonStringEnumConverter))]
publicenum Status
{
[JsonStringEnumMemberName("Ready For Dev")]
ReadyForDev,
[JsonStringEnumMemberName("In Progress")]
InProgress,
[JsonStringEnumMemberName("Completed")]
Completed
}
internal class Program
{
static void Main(string[] args)
{
var status = Status.ReadyForDev;
string json = JsonSerializer.Serialize(status);
Console.WriteLine(json);
Console.ReadKey();
}
}
}
輸出示例
圖片
總結(jié)
.NET 9 為 System.Text.Json 庫帶來了多項重要改進,使其在 JSON 序列化和反序列化方面更加強大、靈活和高效。通過本文的示例代碼,開發(fā)者可以更好地理解和應用這些新特性,從而提升開發(fā)效率和代碼質(zhì)量。