System.Text.Json.JsonSerializer 使用非原始值序列化字典键时忽略 DictionaryKeyPolicy
System.Text.Json.JsonSerializer ignores DictionaryKeyPolicy when serializing dictionary keys with non-primitive values
我有以下代码(.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)的键值时,它工作正常。但是,当值是复杂类型(另一个字典,自定义 class)时,它不起作用。关于如何使序列化程序生成驼峰式密钥的任何建议?
默认情况下,MVC 在 ASP.NET 中使用驼峰式大小写。但是,WebAPI 未配置为使用驼峰式大小写。如果您使用的是 WebAPI,您可以尝试将其添加到您的 Startup.cs
services.AddMvc();
这是 .NET Core 3.x 中的一个已知错误,已在 .NET 5 中修复。请参阅:
System.Text.Json: DictionaryKeyPolicy not applied to keys that contain non primitive types #30889
Possible DictionaryKeyPolicy bug when serializing Dictionary<string, object> #43143.
https://dotnetfiddle.net/ycRUPy 演示 fiddle 您的代码在 .NET 5 中正常工作。
如果您不能迁移到 .NET 5,您将需要引入自定义 a custom JsonConverter
similar to this one from the Microsoft documentation。以下应该完成这项工作:
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
// By https://whosebug.com/users/3542863/sean-rose
// To
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);
演示 fiddle here.
我有以下代码(.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)的键值时,它工作正常。但是,当值是复杂类型(另一个字典,自定义 class)时,它不起作用。关于如何使序列化程序生成驼峰式密钥的任何建议?
默认情况下,MVC 在 ASP.NET 中使用驼峰式大小写。但是,WebAPI 未配置为使用驼峰式大小写。如果您使用的是 WebAPI,您可以尝试将其添加到您的 Startup.cs
services.AddMvc();
这是 .NET Core 3.x 中的一个已知错误,已在 .NET 5 中修复。请参阅:
System.Text.Json: DictionaryKeyPolicy not applied to keys that contain non primitive types #30889
Possible DictionaryKeyPolicy bug when serializing Dictionary<string, object> #43143.
https://dotnetfiddle.net/ycRUPy 演示 fiddle 您的代码在 .NET 5 中正常工作。
如果您不能迁移到 .NET 5,您将需要引入自定义 a custom JsonConverter
similar to this one from the Microsoft documentation。以下应该完成这项工作:
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
// By https://whosebug.com/users/3542863/sean-rose
// To
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);
演示 fiddle here.