使用 System.Text.JSON 将枚举反序列化为字符串的问题

Lea*_*Net 10 c# serialization .net-core asp.net-core system.text.json

我目前正在使用 .NET 6 和 System.Text.Json 进行序列化。当我使用 OkObjectResult 或 ObjectResult 返回响应时,我遇到了 system.text.json 未将枚举正确反序列化为字符串的问题

我在模型上使用了以下内容

public class Customer
{
    public string? id { get; set; }

    public string? Name { get; set; }
    
    public string Address { get; set; }
    
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public CustomerType Type {get; set;}
}

Run Code Online (Sandbox Code Playgroud)
using System.Text.Json.Serialization;

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum CustomerType
{
    NEW,
    EXISTING
}
Run Code Online (Sandbox Code Playgroud)

现在是 API 代码

public async Task<IActionResult> GetCustomerById(string Id)
    {
        var results = await _customerService.GetData(Id);
        // The results have correct JSON data with enum as string but as soon as I pass this to OkObjectResult, it changes the enum back to int
        return new OkObjectResult(results );
           
    }
Run Code Online (Sandbox Code Playgroud)

服务

public async Task<Customer> GetData(string Id)
    {
        var results = await _httpClient.SendAsync(Id);  // Get Data
        var jsonResults = await results.Content.ReadAsStringAsync();
       var options = new JsonSerializerOptions{ Converters ={
        new JsonStringEnumConverter()};

        return JsonSerializer.Deserialize<Customer>(jsonResults ,
            options ) ;  // This returns the data correctly
}

Run Code Online (Sandbox Code Playgroud)

现在我的问题是为什么 OkObjectResult 会破坏代码并返回整数而不是枚举字符串值

Sed*_*glu 4

您需要在启动代码中将枚举转换器引入 ASP.NET,如下所示:

services.AddJsonOptions(options =>
{
   var converter = new JsonStringEnumConverter();
   options.JsonSerializerOptions.Converters.Add(converter);
});
Run Code Online (Sandbox Code Playgroud)