【问题标题】:System.Text.Json.JsonSerializer ignores DictionaryKeyPolicy when serializing dictionary keys with non-primitive valuesSystem.Text.Json.JsonSerializer 在序列化具有非原始值的字典键时忽略 DictionaryKeyPolicy
【发布时间】:2021-01-29 14:17:26
【问题描述】:

我有以下代码(.Net Core 3.1):

var dictionary = new Dictionary<string, object>()
{
    {"Key1", 5},
    {"Key2", "aaa"},
    {"Key3", new Dictionary<string, object>(){ {"Key4", 123}}}
};
var serialized = JsonSerializer.Serialize(dictionary, new JsonSerializerOptions()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
});

我希望序列化变量的字符串如下所示:

{"key1":5,"key2":"aaa","key3":{"key4":123}}

但是我得到的是:

{"key1":5,"key2":"aaa","Key3":{"key4":123}}

我真的不明白为什么有些属性是驼峰式的,而有些则不是。我能够弄清楚的是,当字典包含值为“原始类型”(int,string,DateTime)的键值时,它可以正常工作。但是,当值是复杂类型(另一个字典,自定义类)时,它不起作用。关于如何使序列化程序产生驼峰式密钥的任何建议?

【问题讨论】:

    标签: c# .net-core .net-core-3.1 system.text.json


    【解决方案1】:

    这是 .NET Core 3.x 中的一个已知错误,已在 .NET 5 中修复。请参阅:

    如果您无法迁移到 .NET 5,则需要引入类似于 this one from the Microsoft documentation 的自定义 custom JsonConverter。以下应该可以完成这项工作:

    public class DictionaryWithNamingPolicyConverter : JsonConverterFactory
    {
        // Adapted from DictionaryTKeyEnumTValueConverter
        // https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to?pivots=dotnet-core-3-1#support-dictionary-with-non-string-key
        readonly JsonNamingPolicy namingPolicy;
    
        public DictionaryWithNamingPolicyConverter(JsonNamingPolicy namingPolicy)
            => this.namingPolicy = namingPolicy ?? throw new ArgumentNullException();
            
        public override bool CanConvert(Type typeToConvert)
        {
            // TODO: Tweak this method to include or exclude any dictionary types that you want.
            // Currently it converts any type implementing IDictionary<string, TValue> that has a public parameterless constructor.
            if (typeToConvert.IsPrimitive || typeToConvert == typeof(string))
                return false;
            var parameters = typeToConvert.GetDictionaryKeyValueType();
            return parameters != null && parameters[0] == typeof(string) && typeToConvert.GetConstructor(Type.EmptyTypes) != null;
        }
        
        public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options)
        {
            var types = type.GetDictionaryKeyValueType();
    
            JsonConverter converter = (JsonConverter)Activator.CreateInstance(
                typeof(DictionaryWithNamingPolicyConverterInner<,>).MakeGenericType(new Type[] { type, types[1] }),
                BindingFlags.Instance | BindingFlags.Public,
                binder: null,
                args: new object[] { namingPolicy, options },
                culture: null);
    
            return converter;
        }       
        
        private class DictionaryWithNamingPolicyConverterInner<TDictionary, TValue> : JsonConverter<TDictionary> 
            where TDictionary : IDictionary<string, TValue>, new()
        {
            readonly JsonNamingPolicy namingPolicy;
            readonly JsonConverter<TValue> _valueConverter;
            readonly Type _valueType;
            
            public DictionaryWithNamingPolicyConverterInner(JsonNamingPolicy namingPolicy, JsonSerializerOptions options)
            {
                this.namingPolicy = namingPolicy ?? throw new ArgumentNullException();
                // For performance, cache the value converter and type.
                this._valueType = typeof(TValue);
                this._valueConverter = (_valueType == typeof(object) ? null : (JsonConverter<TValue>)options.GetConverter(typeof(TValue))); // Encountered a bug using the builtin ObjectConverter 
            }
    
            public override TDictionary Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                if (reader.TokenType == JsonTokenType.Null)
                    return default(TDictionary); // Or throw an exception if you prefer.
                if (reader.TokenType != JsonTokenType.StartObject)
                    throw new JsonException();
                var dictionary = new TDictionary();
                while (reader.Read())
                {
                    if (reader.TokenType == JsonTokenType.EndObject)
                        return dictionary;
                    if (reader.TokenType != JsonTokenType.PropertyName)
                        throw new JsonException();
                    var key = reader.GetString();
                    reader.Read();                  
                    dictionary.Add(key, _valueConverter.ReadOrDeserialize<TValue>(ref reader, _valueType, options));
                }
                throw new JsonException();
            }
            
            public override void Write(Utf8JsonWriter writer, TDictionary dictionary, JsonSerializerOptions options)
            {
                writer.WriteStartObject();
                foreach (var pair in dictionary)
                {
                    writer.WritePropertyName(namingPolicy.ConvertName(pair.Key));
                    _valueConverter.WriteOrSerialize(writer, pair.Value, _valueType, options);
                }
                writer.WriteEndObject();
            }
        }
    }
    
    public static class JsonSerializerExtensions
    {
        public static void WriteOrSerialize<T>(this JsonConverter<T> converter, Utf8JsonWriter writer, T value, Type type, JsonSerializerOptions options)
        {
            if (converter != null)
                converter.Write(writer, value, options);
            else
                JsonSerializer.Serialize(writer, value, type, options);
        }
    
        public static T ReadOrDeserialize<T>(this JsonConverter<T> converter, ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            => converter != null ? converter.Read(ref reader, typeToConvert, options) : (T)JsonSerializer.Deserialize(ref reader, typeToConvert, options);
    }
    
    public static class TypeExtensions
    {
        public static IEnumerable<Type> GetInterfacesAndSelf(this Type type)
            => (type ?? throw new ArgumentNullException()).IsInterface ? new[] { type }.Concat(type.GetInterfaces()) : type.GetInterfaces();
    
        public static IEnumerable<Type []> GetDictionaryKeyValueTypes(this Type type)
            => type.GetInterfacesAndSelf().Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IDictionary<,>)).Select(t => t.GetGenericArguments());
    
        public static Type [] GetDictionaryKeyValueType(this Type type)
            => type.GetDictionaryKeyValueTypes().SingleOrDefaultIfMultiple();
    }
    
    public static class LinqExtensions
    {
        // Copied from this answer https://stackoverflow.com/a/25319572
        // By https://stackoverflow.com/users/3542863/sean-rose
        // To https://stackoverflow.com/questions/3185067/singleordefault-throws-an-exception-on-more-than-one-element
        public static TSource SingleOrDefaultIfMultiple<TSource>(this IEnumerable<TSource> source)
        {
            var elements = source.Take(2).ToArray();
            return (elements.Length == 1) ? elements[0] : default(TSource);
        }
    }
    

    然后序列化如下:

    var options = new JsonSerializerOptions
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
        Converters = { new DictionaryWithNamingPolicyConverter(JsonNamingPolicy.CamelCase) },
    };
    var serialized = JsonSerializer.Serialize(dictionary, options);
    

    演示小提琴here.

    【讨论】:

    • 太好了,非常感谢。我不能使用 .Net 5,所以我将使用带有自定义 JsonConverter 的解决方案。
    【解决方案2】:

    默认情况下,MVC 在 ASP.NET 中使用驼峰式大小写。但是,WebAPI 未配置为使用驼峰式。如果您使用的是 WebAPI,您可以尝试将其添加到您的 Startup.cs

    services.AddMvc();
    

    【讨论】:

    • 不,我正在使用 System.Text.Json JsonSerializer
    • 尝试添加 services.AddMvc();到 Startp.cs
    猜你喜欢
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2020-04-16
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多