System.Text.Json.JsonSerializer でクラスフィールドを使用するにはどうすればいいですか? 質問する

System.Text.Json.JsonSerializer でクラスフィールドを使用するにはどうすればいいですか? 質問する

最近、ソリューションをすべて .NET Core 3 にアップグレードしましたが、クラス変数をフィールドにする必要があるクラスがあります。新しいバージョンではSystem.Text.Json.JsonSerializerフィールドのシリアル化もデシリアル化もサポートされておらず、代わりにプロパティのみが処理されるため、これは問題です。

以下の例の 2 つの最終クラスの値が正確に同じであることを保証する方法はありますか?

using System.Text.Json;

public class Car
{
    public int Year { get; set; } // does serialize correctly
    public string Model; // doesn't serialize correctly
}

static void Problem() {
    Car car = new Car()
    {
        Model = "Fit",
        Year = 2008,
    };
    string json = JsonSerializer.Serialize(car); // {"Year":2008}
    Car carDeserialized = JsonSerializer.Deserialize<Car>(json);

    Console.WriteLine(carDeserialized.Model); // null!
}

ベストアンサー1

.NET Core 3.xSystem.Text.Jsonはフィールドをシリアル化しません。ドキュメント:

.NET Core 3.1 の System.Text.Json ではフィールドはサポートされていません。カスタム コンバーターでこの機能を提供できます。

.NET 5以降、パブリックフィールドは設定することでシリアル化できます。JsonSerializerOptions.IncludeFieldsまたはtrueシリアル化するフィールドをマークすることで[JsonInclude]:

using System.Text.Json;

static void Main()
{
    var car = new Car { Model = "Fit", Year = 2008 };

    // Enable support
    var options = new JsonSerializerOptions { IncludeFields = true };

    // Pass "options"
    var json = JsonSerializer.Serialize(car, options);

    // Pass "options"
    var carDeserialized = JsonSerializer.Deserialize<Car>(json, options);

    Console.WriteLine(carDeserialized.Model); // Writes "Fit"
}

public class Car
{
    public int Year { get; set; }
    public string Model;
}

詳細については以下を参照してください。

おすすめ記事