zoukankan      html  css  js  c++  java
  • System.Text.Json 5.0 已增加支持将Enum 由默认 Number类型 转换为String JsonStringEnumConverter

    System.Text.Json 5.0 已增加支持将Enum 由默认 Number类型 转换为String

    System.Text.Json 5.0 增加了 将Enum转换成 字符串的 Converter,效果类似于 NewtonsoftJson

    services
        .AddControllersWithViews(...)
        .AddNewtonsoftJson(options => 
            options.SerializerSettings.Converters.Add(new StringEnumConverter()));
    

    https://docs.microsoft.com/zh-cn/dotnet/api/system.text.json.serialization.jsonstringenumconverter.-ctor?view=net-5.0

    将 全部Enum转换成 String

    使用方式

               services
                    .AddControllers()
                    .AddJsonOptions(options =>
                    {
                        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                    });
    

    源码地址

    https://github.com/dotnet/runtime/blob/master/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonStringEnumConverter.cs

    // Licensed to the .NET Foundation under one or more agreements.
    // The .NET Foundation licenses this file to you under the MIT license.
    
    using System.Reflection;
    using System.Text.Json.Serialization.Converters;
    
    namespace System.Text.Json.Serialization
    {
        /// <summary>
        /// Converter to convert enums to and from strings.
        /// </summary>
        /// <remarks>
        /// Reading is case insensitive, writing can be customized via a <see cref="JsonNamingPolicy" />.
        /// </remarks>
        public sealed class JsonStringEnumConverter : JsonConverterFactory
        {
            private readonly JsonNamingPolicy? _namingPolicy;
            private readonly EnumConverterOptions _converterOptions;
    
            /// <summary>
            /// Constructor. Creates the <see cref="JsonStringEnumConverter"/> with the
            /// default naming policy and allows integer values.
            /// </summary>
            public JsonStringEnumConverter()
                : this(namingPolicy: null, allowIntegerValues: true)
            {
                // An empty constructor is needed for construction via attributes
            }
    
            /// <summary>
            /// Constructor.
            /// </summary>
            /// <param name="namingPolicy">
            /// Optional naming policy for writing enum values.
            /// </param>
            /// <param name="allowIntegerValues">
            /// True to allow undefined enum values. When true, if an enum value isn't
            /// defined it will output as a number rather than a string.
            /// </param>
            public JsonStringEnumConverter(JsonNamingPolicy? namingPolicy = null, bool allowIntegerValues = true)
            {
                _namingPolicy = namingPolicy;
                _converterOptions = allowIntegerValues
                    ? EnumConverterOptions.AllowNumbers | EnumConverterOptions.AllowStrings
                    : EnumConverterOptions.AllowStrings;
            }
    
            /// <inheritdoc />
            public override bool CanConvert(Type typeToConvert)
            {
                return typeToConvert.IsEnum;
            }
    
            /// <inheritdoc />
            public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
            {
                JsonConverter converter = (JsonConverter)Activator.CreateInstance(
                    typeof(EnumConverter<>).MakeGenericType(typeToConvert),
                    BindingFlags.Instance | BindingFlags.Public,
                    binder: null,
                    new object?[] { _converterOptions, _namingPolicy, options },
                    culture: null)!;
    
                return converter;
            }
        }
    }
    
  • 相关阅读:
    Day4
    Day 4 -E
    Day4
    Day4
    Day4
    Day4
    Day4-F-产生冠军 HDU
    Day4
    Day4-B-最短路径问题 HDU3790
    HackerRank
  • 原文地址:https://www.cnblogs.com/WNpursue/p/14378092.html
Copyright © 2011-2022 走看看