System.Text.Json.JsonException: JSON 值无法转换为枚举

System.Text.Json.JsonException: The JSON value could not be converted to enum

我有一个 ASP.NET Core OData Web API,其端点 returns 以下内容:

{
    "@odata.context": "https://localhost:44305/odata/$metadata#OrgUnits",
    "@odata.count": 3,
    "value": [
        {
            "Status": "Active",
            "OperationMode": "Normal",
            "BaseUrl": "https://test.nl/",
            "OrgUnitCode": "TEST",
            "Name": "Test",
            "Address": "Spoorlaan 348",
            "PostalCode": "5038 CC",
            "City": "Tilburg",
            "PhoneNumber": "012 345 6789",
            "ChamberOfCommerceNumber": null,
            "ContactName": null,
            "Website": null,
            "EmailAddress": null,
            "Id": 1,
            "DateCreated": "0001-01-01T00:00:00Z",
            "LastModifiedDate": "0001-01-01T00:00:00Z"
        },

Status 和 OperationMode 是枚举:

    public enum OperationMode
    {
        Inherited = 0,
        Normal = 1,
        Test = 2
    }
    public enum Status
    {
        Inherited = 0,
        Active = 1,
        Inactive = 2
    }
    public class OrgUnit : BaseEntity
    {
        public Status Status { get; set; }
        
        public OperationMode OperationMode { get; set; }
        
        public string BaseUrl { get; set; }
        
        public string OrgUnitCode { get; set; }
        
        public string Name { get; set; }
        
        public string Address { get; set; }
        
        public string PostalCode { get; set; }
        
        public string City { get; set; }
        
        public string PhoneNumber { get; set; }
        
        public string ChamberOfCommerceNumber { get; set; }
        
        public string ContactName { get; set; }
        
        public string Website { get; set; }
        
        public string EmailAddress { get; set; }
    }

在我的前端 Blazor Server 应用程序中,我将响应主体反序列化为 OrgUnitsResponse 对象。此响应对象将用于填充 Telerik 网格组件。

        public async Task<OrgUnitsResponse> GetOrgUnits(DataSourceRequest request)
        {
            var baseUrl = "https://localhost:44305/odata/OrgUnits?";

            var requestUrl = $"{baseUrl}{request.ToODataString()}";

            var requestMessage = new HttpRequestMessage(HttpMethod.Get, requestUrl);
            requestMessage.Headers.Add("Accept", "application/json");
            var client = HttpClient.CreateClient();
            var response = await client.SendAsync(requestMessage);

            if (response.IsSuccessStatusCode)
            {
                var body = await response.Content.ReadAsStringAsync();
                var oDataResponse = JsonSerializer.Deserialize<OrgUnitsResponse>(body);
                return oDataResponse;
            }
            else
            {
                throw new HttpRequestException(
                    "Request failed. I need better error handling, e.g., returning empty data.");
            }
        }
    public class OrgUnitsResponse
    {
        [System.Text.Json.Serialization.JsonPropertyName("value")]
        public List<OrgUnit> OrgUnits { get; set; }
        
        [System.Text.Json.Serialization.JsonPropertyName("@odata.count")]
        public int Total { get; set; }
    }

遗憾的是,这似乎不起作用。我收到以下错误:

System.Text.Json.JsonException: The JSON value could not be converted to Domain.Enums.Status. Path: $.value[0].Status 

如何正确地将 JSON 字符串值反序列化为枚举?

问这个问题1分钟后就已经找到答案了。将其保留在那里,以便其他遇到此问题的人可以阅读。

解决方案是将 JsonStringEnumConverter 作为选项传递给序列化程序。

var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter());
var oDataResponse = JsonSerializer.Deserialize<OrgUnitsResponse>(body, options);