How to use class fields with System.Text.Json.JsonSerializer?

前端 未结 2 2100
情书的邮戳
情书的邮戳 2020-11-27 08:26

I recently upgraded a solution to be all .NET Core 3 and I have a class that requires the class variables to be fields. This is a problem since the new System.Text.Jso

相关标签:
2条回答
  • 2020-11-27 08:58

    Fields now work in the prerelease version (I tried 5.0.0-rc.1.20451.14), but you have to enable the option (details in #34558 and #876):

    // System.Text.Json 5.0.0-rc.1.20451.14
    // 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;
    }
    
    0 讨论(0)
  • 2020-11-27 09:07

    Please try this library I wrote as an extension to System.Text.Json to offer missing features: https://github.com/dahomey-technologies/Dahomey.Json.

    You will find support for fields.

    using System.Text.Json;
    using Dahomey.Json
    
    public class Car
    {
        public int Year { get; set; } // does serialize correctly
        public string Model; // will serialize correctly
    }
    
    static void Problem() {
        JsonSerializerOptions options = new JsonSerializerOptions();
        options.SetupExtensions(); // extension method to setup Dahomey.Json extensions
    
        Car car = new Car()
        {
            Model = "Fit",
            Year = 2008,
        };
        string json = JsonSerializer.Serialize(car, options); // {"Year":2008,"Model":"Fit"}
        Car carDeserialized = JsonSerializer.Deserialize<Car>(json);
    
        Console.WriteLine(carDeserialized.Model); // Fit
    }
    
    0 讨论(0)
提交回复
热议问题