bre*_*vhb 4 c# .net-core system.text.json
是否可以使用 System.Text.Json 将字典序列化(和反序列化)为数组?
相反,{ "hello": "world" }我需要将我的字典序列化为{ "key": "hello", "value": "world" }最好,而不必在我的类的字典属性上设置属性。
使用 newtonsoft.json 可以这样:
class DictionaryAsArrayResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (objectType.GetInterfaces().Any(i => i == typeof(IDictionary) ||
(i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>))))
{
return base.CreateArrayContract(objectType);
}
return base.CreateContract(objectType);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用为要序列化为数组的每种字典类型JsonConverterFactory创建特定的字典类型来执行此操作。JsonConverter<T>这是一个这样的转换器,适用于实现以下功能的每个类IDictionary<TKey, TValue>:
public class DictionaryConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert.IsClass && typeToConvert.GetDictionaryKeyValueType() != null && typeToConvert.GetConstructor(Type.EmptyTypes) != null;
}
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
var keyValueTypes = typeToConvert.GetDictionaryKeyValueType();
var converterType = typeof(DictionaryAsArrayConverter<,,>).MakeGenericType(typeToConvert, keyValueTypes.Value.Key, keyValueTypes.Value.Value);
return (JsonConverter)Activator.CreateInstance(converterType);
}
}
public class DictionaryAsArrayConverter<TKey, TValue> : DictionaryAsArrayConverter<Dictionary<TKey, TValue>, TKey, TValue>
{
}
public class DictionaryAsArrayConverter<TDictionary, TKey, TValue> : JsonConverter<TDictionary> where TDictionary : class, IDictionary<TKey, TValue>, new()
{
struct KeyValueDTO
{
public TKey Key { get; set; }
public TValue Value { get; set; }
}
public override TDictionary Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var list = JsonSerializer.Deserialize<List<KeyValueDTO>>(ref reader, options);
if (list == null)
return null;
var dictionary = typeToConvert == typeof(Dictionary<TKey, TValue>) ? (TDictionary)(object)new Dictionary<TKey, TValue>(list.Count) : new TDictionary();
foreach (var pair in list)
dictionary.Add(pair.Key, pair.Value);
return dictionary;
}
public override void Write(Utf8JsonWriter writer, TDictionary value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value.Select(p => new KeyValueDTO { Key = p.Key, Value = p.Value }), options);
}
}
public static class TypeExtensions
{
public static IEnumerable<Type> GetInterfacesAndSelf(this Type type)
{
if (type == null)
throw new ArgumentNullException();
if (type.IsInterface)
return new[] { type }.Concat(type.GetInterfaces());
else
return type.GetInterfaces();
}
public static KeyValuePair<Type, Type>? GetDictionaryKeyValueType(this Type type)
{
KeyValuePair<Type, Type>? types = null;
foreach (var pair in type.GetDictionaryKeyValueTypes())
{
if (types == null)
types = pair;
else
return null;
}
return types;
}
public static IEnumerable<KeyValuePair<Type, Type>> GetDictionaryKeyValueTypes(this Type type)
{
foreach (Type intType in type.GetInterfacesAndSelf())
{
if (intType.IsGenericType
&& intType.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
var args = intType.GetGenericArguments();
if (args.Length == 2)
yield return new KeyValuePair<Type, Type>(args[0], args[1]);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后将工厂添加到JsonSerializerOptions.Converters本地,如下:
var options = new JsonSerializerOptions
{
Converters = { new DictionaryConverterFactory() },
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
var json = JsonSerializer.Serialize(dictionary, options);
var dictionary2 = JsonSerializer.Deserialize<TDictionary>(json, options);
Run Code Online (Sandbox Code Playgroud)
或者在 ASP.NET Core 中进行全局设置,如如何在 asp.net core 3 中设置 json 序列化器设置所示?:
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new DictionaryConverterFactory());
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
Run Code Online (Sandbox Code Playgroud)
DictionaryAsArrayConverter<TKey, TValue>如果您只想将某些字典类型序列化为数组,也可以直接使用底层的单独转换器。
笔记:
JsonSerializerPropertyNamingPolicy目前在序列化时不尊重KeyValuePair<TKey, TValue>(请参阅问题#1197),因此我必须引入 aKeyValueDTO来获取外壳"key"并"value"根据您的问题的要求。
我没有实现非泛型IDictionary类型的转换器。这可以作为答案的延伸来完成。
有关转换器工厂模式的更多信息,请参阅如何在 .NET 中编写用于 JSON 序列化的自定义转换器:示例工厂模式转换器
DefaultContractResolver与in System.Text.Json--JsonClassInfo和--等效的类型JsonPropertyInfo是内部类型。System.Text.Json #42001 中有一个 DefaultContractResolver 的开放增强等效项,要求提供公共等效项。
演示小提琴在这里。
| 归档时间: |
|
| 查看次数: |
6902 次 |
| 最近记录: |