必須プロパティ

.NET 7 以降では、特定のプロパティをマークして、逆シリアル化を成功させるために JSON ペイロードにプロパティが存在する必要があることを示すことができます。 これらの必須プロパティの 1 つ以上が存在しない場合、JsonSerializer.Deserialize メソッドは JsonException をスローします。

JSON の逆シリアル化に必要なプロパティまたはフィールドをマークするには、次の 3 つの方法があります。

シリアライザーの観点からは、これら 2 つの区別は同等であり、両方とも同じメタデータ 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);