如何将自定义 JsonConverter 应用于字典中列表中的值?

How to apply a custom JsonConverter to the values inside a list inside a dictionary?

我有一个 CustomConverter : JsonConverter<int> 整数,我需要将 [JsonConverter(typeof(CustomConverter))] 属性添加到 Dictionary<string, List<int>> 属性。将自定义转换器应用于 intListDictionary 效果很好:

public class Example 
{
    [JsonConverter(typeof(CustomConverter))]
    public int ExampleInt { get; set; }
    [JsonProperty(ItemConverterType = typeof(CustomConverter))]
    public List<int> ExampleList { get; set; }
    
    // How do I specify the Converter attribute for the int in the following line?
    public Dictionary<string, List<int>> ExampleDictionary { get; set; }
}

但是我不知道如何指定 CustomConverter 应该用于 DictionaryList 内的 int 值。我该怎么做?

要实现此功能,您需要创建 CustomClass 并继承它 IDictionary

public class CustomClass : IDictionary<string, List<int>>

然后你可以使用这个 class 像下面这样的东西:

public class Example {
   [JsonConverter(typeof(CustomConverter)]
   public string ExampleString { get; set; }
   [JsonProperty(ItemConverterType = typeof(CustomConverter))]
   public List<int> ExampleList { get; set; }
   [JsonProperty(ItemConverterType = typeof(CustomConverter))]
   public CustomClass data { get; set; }
}

让我知道您需要任何其他信息。

Dictionary<string, List<int>> 是 collection 的嵌套 collection,您正在寻找类似 ItemOfItemsConverterType 的东西,对应于 ItemConverterType,以指定一个collection 的项目的项目转换器。不幸的是,没有实现这样的属性。相反,有必要为嵌套的 List<int> collection 创建一个转换器,调用所需的最里面的项目转换器。

这可以通过为 List<> 实施以下 JsonConverter decorator 来完成:

public class ListItemConverterDecorator : JsonConverter
{
    readonly JsonConverter itemConverter;
    
    public ListItemConverterDecorator(Type type) => 
        itemConverter = (JsonConverter)Activator.CreateInstance(type ?? throw new ArgumentNullException());

    public override bool CanConvert(Type objectType) =>
        !objectType.IsPrimitive && objectType != typeof(string) && objectType.BaseTypesAndSelf().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>));
    
    public override bool CanRead => itemConverter.CanRead;
    public override bool CanWrite => itemConverter.CanWrite;
    
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var itemType = objectType.BaseTypesAndSelf().Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>)).Select(t => t.GetGenericArguments()[0]).First();
        if (reader.MoveToContentAndAssert().TokenType == JsonToken.Null)
            return null;
        if (reader.TokenType != JsonToken.StartArray)
            throw new JsonSerializationException(string.Format("Unexpected token {0}, expected {1}", reader.TokenType, JsonToken.StartArray));
        var list = existingValue as IList ?? (IList)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
        while (reader.ReadToContentAndAssert().TokenType != JsonToken.EndArray)
            list.Add(itemConverter.ReadJson(reader, itemType, null, serializer));
        return list;
    }
    
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteStartArray();
        foreach (var item in (IList)value)
            if (item == null)
                writer.WriteNull();
            else
                itemConverter.WriteJson(writer, item, serializer);
        writer.WriteEndArray();
    }
}

public static partial class JsonExtensions
{
    public static JsonReader ReadToContentAndAssert(this JsonReader reader) =>
        reader.ReadAndAssert().MoveToContentAndAssert();

    public static JsonReader MoveToContentAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (reader.TokenType == JsonToken.None)       // Skip past beginning of stream.
            reader.ReadAndAssert();
        while (reader.TokenType == JsonToken.Comment) // Skip past comments.
            reader.ReadAndAssert();
        return reader;
    }

    public static JsonReader ReadAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (!reader.Read())
            throw new JsonReaderException("Unexpected end of JSON stream.");
        return reader;
    }
}

public static class TypeExtensions
{
    public static IEnumerable<Type> BaseTypesAndSelf(this Type type)
    {
        while (type != null)
        {
            yield return type;
            type = type.BaseType;
        }
    }
}

然后将你的Exampleclass注释如下,使用JsonPropertyAttribute.ItemConverterParameters指定内项转换器CustomConverter:

public class Example 
{
    [JsonConverter(typeof(CustomConverter))]
    public int ExampleInt { get; set; }
    [JsonProperty(ItemConverterType = typeof(CustomConverter))]
    public List<int> ExampleList { get; set; }
    
    [JsonProperty(ItemConverterType = typeof(ListItemConverterDecorator), 
                  ItemConverterParameters = new object [] { typeof(CustomConverter) })]
    public Dictionary<string, List<int>> ExampleDictionary { get; set; }
}

现在你应该准备好了。演示 fiddle here.