.NET 9 中 System.Text.Json 庫(kù)的全面升級(jí)與實(shí)踐指南
在 .NET 9 中,System.Text.Json 庫(kù)得到了顯著增強(qiáng),為開(kāi)發(fā)者提供了更強(qiáng)大和靈活的 JSON 處理能力。這些改進(jìn)主要集中在 JSON 架構(gòu)支持、智能應(yīng)用功能以及序列化和反序列化過(guò)程的自定義選項(xiàng)上。本文將詳細(xì)介紹這些新特性,并提供示例代碼,幫助開(kāi)發(fā)者更好地理解和應(yīng)用這些功能。
JSON 架構(gòu)導(dǎo)出器
在 .NET 9 中,新增了 JsonSchemaExporter 類(lèi),使開(kāi)發(fā)者能夠從 .NET 類(lèi)型中提取 JSON 架構(gòu)文檔。這一特性有助于驗(yàn)證和文檔化 JSON 數(shù)據(jù)結(jié)構(gòu),確保應(yīng)用程序之間的一致性。
示例代碼
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();
}
}
}
輸出示例
圖片
可空引用類(lèi)型支持
為了與 C# 的可空引用類(lèi)型注釋保持一致,System.Text.Json 現(xiàn)在提供了 RespectNullableAnnotations 選項(xiàng)。當(dāng)啟用時(shí),序列化和反序列化過(guò)程中會(huì)強(qiáng)制執(zhí)行不可空引用類(lèi)型,若不可空屬性被賦值為 null,則會(huì)拋出異常。
示例代碼
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();
}
}
}
輸出示例
圖片
自定義序列化縮進(jìn)
System.Text.Json 引入了自定義縮進(jìn)選項(xiàng),允許開(kāi)發(fā)者指定用于縮進(jìn)的字符和大小,以滿(mǎn)足特定的格式要求。這有助于使 JSON 輸出更易讀。
示例代碼
var options = new JsonSerializerOptions
{
WriteIndented = true
};
var json = JsonSerializer.Serialize(new { Name = "Alice", Age = 30 }, options);
Console.WriteLine(json);
輸出示例
圖片
JsonSerializerOptions.Web
JsonSerializerOptions.Web 提供了一組預(yù)定義的選項(xiàng),專(zhuān)為 Web 應(yīng)用程序量身定制。這包括屬性名稱(chēng)的 camelCase 格式和靈活的數(shù)字處理,使 JSON 序列化符合常見(jiàn)的 Web API 實(shí)踐。
示例代碼
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 類(lèi)現(xiàn)在允許開(kāi)發(fā)者控制 JSON 對(duì)象中屬性的順序。這在某些序列化場(chǎng)景中尤其有用,或者在與對(duì)屬性順序敏感的系統(tǒng)交互時(shí)。
示例代碼
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 庫(kù)引入了 JsonElement.DeepEquals 方法,使得兩個(gè) JsonElement 實(shí)例之間的深度比較變得更加簡(jiǎn)單。該方法可以判斷兩個(gè) JSON 元素在結(jié)構(gòu)和語(yǔ)義上是否相同。
示例代碼
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();
}
}
輸出示例
圖片
自定義枚舉成員名稱(chēng)
在 .NET 9 中,System.Text.Json 庫(kù)引入了 JsonStringEnumMemberName 屬性,允許開(kāi)發(fā)者自定義單個(gè)枚舉成員的 JSON 表示。這一增強(qiáng)提供了更大的靈活性,尤其是在需要特定命名約定或格式的場(chǎng)景中。
示例代碼
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 庫(kù)帶來(lái)了多項(xiàng)重要改進(jìn),使其在 JSON 序列化和反序列化方面更加強(qiáng)大、靈活和高效。通過(guò)本文的示例代碼,開(kāi)發(fā)者可以更好地理解和應(yīng)用這些新特性,從而提升開(kāi)發(fā)效率和代碼質(zhì)量。