mac*_*pak 3 c# .net-core .net-core-3.1 system.text.json
我有以下代码(.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,
});
Run Code Online (Sandbox Code Playgroud)
我希望序列化变量有一个如下所示的字符串:
{"key1":5,"key2":"aaa","key3":{"key4":123}}
Run Code Online (Sandbox Code Playgroud)
然而我得到的是:
{"key1":5,"key2":"aaa","Key3":{"key4":123}}
Run Code Online (Sandbox Code Playgroud)
我真的不明白为什么有些属性是驼峰式的,有些不是。我能够弄清楚的是,当字典包含键值,其中值是“原始类型”(int、string、DateTime)时,它可以正常工作。但是,当该值是复杂类型(另一个字典,自定义类)时,它不起作用。关于如何使序列化器生成驼峰式密钥有什么建议吗?
这是 .NET Core 3.x 中的一个已知错误,已在 .NET 5 中修复。请参阅:
序列化 Dictionary<string, object> 时可能存在 DictionaryKeyPolicy 错误 #43143。
https://dotnetfiddle.net/ycRUPy用于演示代码在 .NET 5 中正常工作。
如果您无法迁移到 .NET 5,则需要引入与 Microsoft 文档中的此自定义类似的自定义JsonConverter。以下应该完成这项工作:
public class DictionaryWithNamingPolicyConverter : JsonConverterFactory
{
// Adapted from DictionaryTKeyEnumTValueConverter
// https://learn.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 /sf/answers/1772370071/
// By /sf/users/248000441/
// To /sf/ask/222954721/
public static TSource SingleOrDefaultIfMultiple<TSource>(this IEnumerable<TSource> source)
{
var elements = source.Take(2).ToArray();
return (elements.Length == 1) ? elements[0] : default(TSource);
}
}
Run Code Online (Sandbox Code Playgroud)
然后序列化如下:
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
Converters = { new DictionaryWithNamingPolicyConverter(JsonNamingPolicy.CamelCase) },
};
var serialized = JsonSerializer.Serialize(dictionary, options);
Run Code Online (Sandbox Code Playgroud)
演示小提琴在这里。
| 归档时间: |
|
| 查看次数: |
5549 次 |
| 最近记录: |