首页 > 解决方案 > System.Text.Json.JsonException:无法将 JSON 值转换为枚举

问题描述

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

{
    "@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 服务器应用程序)上,我将响应主体反序列化为一个 OrgUnitsResponse 对象。此响应对象将用于填充 Telerik Grid 组件。

        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 字符串值反序列化为枚举?

标签: jsonasp.net-coredeserializationodata

解决方案


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

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

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

推荐阅读