16

我正在将我的代码从 .NET Core 2.x 转移到 .NET Core 3.x(即使用本机库System.Text.Json)。在这样做的过程中,我遇到了一些问题,即以前Newtonsoft.Json对可空枚举的支持目前没有明确的迁移路径——.NET Core 3.x 似乎不支持它?

例如,使用Newtonsoft.JsonJSON 转换器支持可为空的枚举,如下所示:

public enum UserStatus
{
    NotConfirmed,
    Active,
    Deleted
}

public class User
{
    public string UserName { get; set; }

    [JsonConverter(typeof(StringEnumConverter))]  // using Newtonsoft.Json
    public UserStatus? Status { get; set; }       // Nullable Enum
}

本机库的当前版本System.Text.Json,似乎不支持这一点。

我该如何解决这个问题?我无法迁移我的代码!

4

5 回答 5

16

不幸的是,目前不支持“开箱即用”System.Text.Json来转换可为空的枚举。

但是,有一个解决方案是使用您自己的自定义转换器(见下文)


解决方案。使用自定义转换器。

您可以通过使用自定义转换器装饰它来将其附加到您的属性:

// using System.Text.Json
[JsonConverter(typeof(StringNullableEnumConverter<UserStatus?>))]  // Note the '?'
public UserStatus? Status { get; set; }                            // Nullable Enum

这是转换器:

public class StringNullableEnumConverter<T> : JsonConverter<T>
{
    private readonly JsonConverter<T> _converter;
    private readonly Type _underlyingType;

    public StringNullableEnumConverter() : this(null) { }

    public StringNullableEnumConverter(JsonSerializerOptions options)
    {
        // for performance, use the existing converter if available
        if (options != null)
        {
            _converter = (JsonConverter<T>)options.GetConverter(typeof(T));
        }

        // cache the underlying type
        _underlyingType = Nullable.GetUnderlyingType(typeof(T));
    }

    public override bool CanConvert(Type typeToConvert)
    {
        return typeof(T).IsAssignableFrom(typeToConvert);
    }

    public override T Read(ref Utf8JsonReader reader, 
        Type typeToConvert, JsonSerializerOptions options)
    {
        if (_converter != null)
        {
            return _converter.Read(ref reader, _underlyingType, options);
        }

        string value = reader.GetString();

        if (String.IsNullOrEmpty(value)) return default;

        // for performance, parse with ignoreCase:false first.
        if (!Enum.TryParse(_underlyingType, value, 
            ignoreCase: false, out object result) 
        && !Enum.TryParse(_underlyingType, value, 
            ignoreCase: true, out result))
        {
            throw new JsonException(
                $"Unable to convert \"{value}\" to Enum \"{_underlyingType}\".");
        }

        return (T)result;
    }

    public override void Write(Utf8JsonWriter writer, 
        T value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value?.ToString());
    }
}

希望在不需要自定义转换器的本地支持之前有所帮助!

于 2019-12-17T18:11:21.023 回答
3

我发现 Svek 的回答非常有帮助,但是我希望转换器与可空和不可空枚举属性兼容。

我通过如下调整他的转换器来实现这一点:

public class JsonNullableEnumStringConverter<TEnum> : JsonConverter<TEnum>
{
    private readonly bool _isNullable;
    private readonly Type _enumType;

    public JsonNullableEnumStringConverter() {
        _isNullable = Nullable.GetUnderlyingType(typeof(TEnum)) != null;

        // cache the underlying type
        _enumType = _isNullable ? 
            Nullable.GetUnderlyingType(typeof(TEnum)) : 
            typeof(TEnum);
    }

    public override TEnum Read(ref Utf8JsonReader reader,
        Type typeToConvert, JsonSerializerOptions options)
    {
        var value = reader.GetString();

        if (_isNullable && string.IsNullOrEmpty(value))
            return default; //It's a nullable enum, so this returns null. 
        else if (string.IsNullOrEmpty(value))
            throw new InvalidEnumArgumentException(
                $"A value must be provided for non-nullable enum property of type {typeof(TEnum).FullName}");

        // for performance, parse with ignoreCase:false first.
        if (!Enum.TryParse(_enumType, value, false, out var result)
            && !Enum.TryParse(_enumType, value, true, out result))
        {
            throw new JsonException(
                $"Unable to convert \"{value}\" to Enum \"{_enumType}\".");
        }

        return (TEnum)result;
    }

    public override void Write(Utf8JsonWriter writer,
        TEnum value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value?.ToString());
    }
}

我还遗漏了一些我的解决方案中不需要的元素。希望这对那里的人有帮助。

于 2021-02-16T16:05:28.707 回答
3

它现在在 5.0 中受支持 -使用 JsonConverterAttribute 指定的 Nullable<T> 的基础类型的荣誉转换器

于 2021-04-16T14:42:39.820 回答
1

另一种选择是通过选项配置对可空枚举的支持:

        JsonSerializerOptions JsonOptions = new()
        {
            Converters =
            {
                new JsonNullableStringEnumConverter(),
            },
        };

来源JsonNullableStringEnumConverter如下:

#nullable enable

    public class JsonNullableStringEnumConverter : JsonConverterFactory
    {
        readonly JsonStringEnumConverter stringEnumConverter;

        public JsonNullableStringEnumConverter(JsonNamingPolicy? namingPolicy = null, bool allowIntegerValues = true)
        {
            stringEnumConverter = new(namingPolicy, allowIntegerValues);
        }

        public override bool CanConvert(Type typeToConvert)
            => Nullable.GetUnderlyingType(typeToConvert)?.IsEnum == true;

        public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        {
            var type = Nullable.GetUnderlyingType(typeToConvert)!;
            return (JsonConverter?)Activator.CreateInstance(typeof(ValueConverter<>).MakeGenericType(type),
                stringEnumConverter.CreateConverter(type, options));
        }

        class ValueConverter<T> : JsonConverter<T?>
            where T : struct, Enum
        {
            readonly JsonConverter<T> converter;

            public ValueConverter(JsonConverter<T> converter)
            {
                this.converter = converter;
            }

            public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                if (reader.TokenType == JsonTokenType.Null)
                {
                    reader.Read();
                    return null;
                }
                return converter.Read(ref reader, typeof(T), options);
            }

            public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
            {
                if (value == null)
                    writer.WriteNullValue();
                else
                    converter.Write(writer, value.Value, options);
            }
        }
    }
于 2021-03-29T11:04:18.530 回答
0

您应该能够通过安装Newtonsoft JSON nuget并将其放置在您的代码中来恢复您的原始行为,我想您正在迁移一个 ASP 应用程序:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
        .AddNewtonsoftJson();
}
于 2019-12-31T13:37:02.843 回答