必要屬性
從 .NET 7 開始,您可以標記特定屬性,表示它們必須存在於 JSON 承載中,還原序列化才能成功。 如果這其中一或多個必要屬性不存在,JsonSerializer.Deserialize 方法就會擲回 JsonException。
有三種方式可將屬性或欄位標記為 JSON 還原序列化所需的項目:
- 新增必要的修飾元,此為 C# 11 的新功能。
- 使用 JsonRequiredAttribute 進行標註,此為 .NET 7 的新功能。
- 修改合約模型的 JsonPropertyInfo.IsRequired 屬性,此為 .NET 7 的新功能。
從序列化程式的觀點來看,這兩個劃分都一樣,而且這兩者都會對應至相同的中繼資料片段,也就是 JsonPropertyInfo.IsRequired。 在大部分情況下,您只要使用內建的 C# 關鍵字即可。 不過,在下列情況下,您應該改用 JsonRequiredAttribute:
- 如果您使用的是 C# 或舊版 C# 以外的程式設計語言。
- 如果您只想將需求套用至 JSON 還原序列化。
- 如果您在來源產生模式中使用
System.Text.Json
序列化。 在此情況下,如果您使用required
修飾元,您的程式碼將不會編譯,因為來源產生會在編譯時間發生。
下列程式碼片段顯示使用 required
關鍵字修改的屬性範例。 此屬性必須存在於 JSON 承載中,還原序列化才能成功。
using System.Text.Json;
// The following line throws a JsonException at run time.
Console.WriteLine(JsonSerializer.Deserialize<Person>("""{"Age": 42}"""));
public class Person
{
public required string Name { get; set; }
public int Age { get; set; }
}
或者,您可以使用 JsonRequiredAttribute:
using System.Text.Json;
// The following line throws a JsonException at run time.
Console.WriteLine(JsonSerializer.Deserialize<Person>("""{"Age": 42}"""));
public class Person
{
[JsonRequired]
public string Name { get; set; }
public int Age { get; set; }
}
您也可以使用 JsonPropertyInfo.IsRequired 屬性,透過合約模型來控制是否需要屬性:
var options = new JsonSerializerOptions
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers =
{
static typeInfo =>
{
if (typeInfo.Kind != JsonTypeInfoKind.Object)
return;
foreach (JsonPropertyInfo propertyInfo in typeInfo.Properties)
{
// Strip IsRequired constraint from every property.
propertyInfo.IsRequired = false;
}
}
}
}
};
// Deserialization now succeeds even though the Name property isn't in the JSON payload.
JsonSerializer.Deserialize<Person>("""{"Age": 42}""", options);