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

前端 未结 2 2113
情书的邮戳
情书的邮戳 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 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(json);
    
        Console.WriteLine(carDeserialized.Model); // Fit
    }
    

提交回复
热议问题