我正在try 使用c#选项模式读取json文件.但是,我遇到了这样一个问题:除非我将其键更改为字符串,否则Dictionary<int,myClass&>的属性无法正确映射,如Dictionary<字符串,myClass&>;

这是我的示例json文件:test.json

{
  "TestMap": [
    {
      "SenderID": "RIMC_EVAC_ZONES",
      "FeedType": null,
      "CategoryMappings": {
        "4": {
          "CategoryID": 4,
          "VccCategoryName": "Local Disaster",
          "ReiCategoryName": "Local Disaster",
          "SubcategoryMappings": {
            "177": [
              {
                "SubcategoryID": 177,
                "ParentCategoryID": 4,
                "VccSubcategoryName": "Evacuation",
                "ReiSubcategoryName": "Evacuation"
              }
            ]
          }
        }
      }
    },
    {
      "SenderID": "EARLY_HURRICANE",
      "FeedType": null,
      "CategoryMappings": {
        "16": {
          "CategoryID": 16,
          "VccCategoryName": "Tropical Storm",
          "ReiCategoryName": "Tropical Storm",
          "SubcategoryMappings": null
        }
      }
    }
  ]
}

这是我的模型:

public class Sender {
    public string SenderID { get; set; }
    public string FeedType { get; set; }
    
    //[JsonConverter(typeof(IntKeyDictionaryConverter))]    
    public Dictionary<int, CategoryMapping> CategoryMappings { get; set; }
}

public class CategoryMapping {
    public int CategoryID { get; set; }
    public string VccCategoryName { get; set; }
    public string ReiCategoryName { get; set; }
    
    public Dictionary<int, List<SubcategoryMapping>> SubcategoryMappings { get; set; }
}

public class SubcategoryMapping
{
    public int SubcategoryID { get; set; }
    public int ParentCategoryID { get; set; }
    public string VccSubcategoryName { get; set; }
    public string ReiSubcategoryName { get; set; }
}

如何注册页面:

builder.Configuration.AddJsonFile("Properties/test.json", optional: true, reloadOnChange: true)

以及我是如何打电话来检索数据的:

List<Sender> people = Configuration.GetSection("TestMap").Get<List<Sender>>();

Problem:: 在我当前的模型中,变量"People"的CategoryMap将为空,但将正确检索其他信息,如SenderID或FeedType.

但是,如果我将"CategoryingMappings"更改为Dictionary<string, CategoryMapping>,那么它将被正确映射.同样的事情也发生在CategoryMap类的"子类别映射"属性上.

我try 过的方法:我try 编写自定义转换器,但它不起作用,并导致转换失败

public class IntKeyDictionaryConverter : JsonConverter<Dictionary<int, CategoryMapping>>
{
    public override Dictionary<int, CategoryMapping> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var dictionary = new Dictionary<int, CategoryMapping>();
    
        if (reader.TokenType != JsonTokenType.StartObject)
        {
            throw new JsonException();
        }

        while (reader.Read())
        {
            if (reader.TokenType == JsonTokenType.EndObject)
            {
                return dictionary;
            }

            if (reader.TokenType == JsonTokenType.PropertyName)
            {
                int key = int.Parse(reader.GetString());
                reader.Read(); 
                CategoryMapping value = JsonSerializer.Deserialize<CategoryMapping>(ref reader, options);
                dictionary.Add(key, value);
            }
        }

        throw new JsonException();
    }

    public override void Write(Utf8JsonWriter writer, Dictionary<int, CategoryMapping> value, JsonSerializerOptions options) {
    }
}

What I need help with:在将json读入我的类对象时,我希望使用整数作为键.我怎样才能做到这一点?

推荐答案

你的问题是Microsoft.Extensions.Configuration.Binder does not use System.Text.Json to deserialize JSON.相反,它手动将JSON解析为IConfigurationSection个元素,然后使用反射将这些元素绑定到POCO.所有这些似乎都没有记录在案,所以为了确认,你可以判断source code for ConfigurationBinder.

.NET 6中,方法BindDictionary()用于绑定到词典.它对字典键类型的注释限制为string和枚举类型:

private static void BindDictionary(
   object dictionary,
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
    Type dictionaryType,
    IConfiguration config, BinderOptions options)
{
    // IDictionary<K,V> is guaranteed to have exactly two parameters
    Type keyType = dictionaryType.GenericTypeArguments[0];
    Type valueType = dictionaryType.GenericTypeArguments[1];
    bool keyTypeIsEnum = keyType.IsEnum;

    if (keyType != typeof(string) && !keyTypeIsEnum)
    {
        // We only support string and enum keys
        return;
    }

.NET 7中,存在包含明确支持数字键的逻辑(经由PR #71609添加)的附加方法BindDictionaryInterface():

private static object? BindDictionaryInterface(
    object? source,
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
    Type dictionaryType,
    IConfiguration config, BinderOptions options)
{
    // IDictionary<K,V> is guaranteed to have exactly two parameters
    Type keyType = dictionaryType.GenericTypeArguments[0];
    Type valueType = dictionaryType.GenericTypeArguments[1];
    bool keyTypeIsEnum = keyType.IsEnum;
    bool keyTypeIsInteger =
        keyType == typeof(sbyte) ||
        keyType == typeof(byte) ||
        keyType == typeof(short) ||
        keyType == typeof(ushort) ||
        keyType == typeof(int) ||
        keyType == typeof(uint) ||
        keyType == typeof(long) ||
        keyType == typeof(ulong);

    if (keyType != typeof(string) && !keyTypeIsEnum && !keyTypeIsInteger)
    {
        // We only support string, enum and integer (except nint-IntPtr and nuint-UIntPtr) keys
        return null;
    }

这解释了为什么只有在迁移到.NET 7后才能成功绑定public Dictionary<int, CategoryMapping> CategoryMappings { get; set; }属性.

如果您不能迁移到.NET7,但仍然需要使用带有整数键的字典,那么as a workaround您可以使用adapter pattern将您的整数字典包装在IDictionary<string, TValue>个替代字典中.

首先,定义以下IntegerDictionaryAdapter<TValue>个类:

public class IntegerDictionaryAdapter<TValue> : AdapterDictionary<int, string, TValue>
{
    static int ToInt(string value) => int.Parse(value, NumberFormatInfo.InvariantInfo);
    static string ToString(int value) => value.ToString(NumberFormatInfo.InvariantInfo);

    public IntegerDictionaryAdapter() : base(new Dictionary<int, TValue>(), s => ToInt(s), i => ToString(i)) { }
    public IntegerDictionaryAdapter(IDictionary<int, TValue> dictionary) : base(dictionary, s => ToInt(s), i => ToString(i)) { }
}

public class AdapterDictionary<TKeyIn, TKeyOut, TValue> : IDictionary<TKeyOut, TValue>
{
    readonly IDictionary<TKeyIn, TValue> dictionary;
    readonly Func<TKeyIn, TKeyOut> mapKeyToOuter;
    readonly Func<TKeyOut, TKeyIn> mapKeyToInner;

    public AdapterDictionary(IDictionary<TKeyIn, TValue> dictionary, Func<TKeyOut, TKeyIn> mapKeyToInner, Func<TKeyIn, TKeyOut> mapKeyToOuter)
    {
        this.dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
        this.mapKeyToInner = mapKeyToInner ?? throw new ArgumentNullException(nameof(mapKeyToInner));
        this.mapKeyToOuter = mapKeyToOuter ?? throw new ArgumentNullException(nameof(mapKeyToOuter));
    }

    public IDictionary<TKeyIn, TValue> UnderlyingDictionary => dictionary;

    KeyValuePair<TKeyIn, TValue> MapItemToOuter(KeyValuePair<TKeyOut, TValue> item) { return new KeyValuePair<TKeyIn, TValue>(mapKeyToInner(item.Key), item.Value); }
    KeyValuePair<TKeyOut, TValue> MapItemFromOuter(KeyValuePair<TKeyIn, TValue> item) { return new KeyValuePair<TKeyOut, TValue>(mapKeyToOuter(item.Key), item.Value); }
    public void Add(TKeyOut key, TValue value) { dictionary.Add(mapKeyToInner(key), value); }
    public bool ContainsKey(TKeyOut key) { return dictionary.ContainsKey(mapKeyToInner(key)); }
    public ICollection<TKeyOut> Keys => new CollectionAdapter<TKeyIn, TKeyOut>(() => dictionary.Keys, mapKeyToOuter, mapKeyToInner);
    public bool Remove(TKeyOut key) { return dictionary.Remove(mapKeyToInner(key)); }
    public bool TryGetValue(TKeyOut key, out TValue value) { return dictionary.TryGetValue(mapKeyToInner(key), out value); }
    public ICollection<TValue> Values { get { return dictionary.Values; } }

    public TValue this[TKeyOut key]
    {
        get { return dictionary[mapKeyToInner(key)]; }
        set { dictionary[mapKeyToInner(key)] = value; }
    }

    public void Add(KeyValuePair<TKeyOut, TValue> item) { dictionary.Add(MapItemToOuter(item)); }
    public void Clear() { dictionary.Clear(); }
    public bool Contains(KeyValuePair<TKeyOut, TValue> item) { return dictionary.Contains(MapItemToOuter(item)); }
    public void CopyTo(KeyValuePair<TKeyOut, TValue>[] array, int arrayIndex)  => this.CopyToArray(array, arrayIndex);
    public int Count { get { return dictionary.Count; } }
    public bool IsReadOnly { get { return dictionary.IsReadOnly; } }
    public bool Remove(KeyValuePair<TKeyOut, TValue> item) { return dictionary.Remove(MapItemToOuter(item)); }
    public IEnumerator<KeyValuePair<TKeyOut, TValue>> GetEnumerator() { return dictionary.Select(i => MapItemFromOuter(i)).GetEnumerator(); }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); }
}

public abstract class CollectionAdapterBase<TIn, TOut, TCollection> : ICollection<TOut> 
    where TCollection : ICollection<TIn>
{
    readonly Func<TCollection> getCollection;
    readonly Func<TIn, TOut> toOuter;

    public CollectionAdapterBase(Func<TCollection> getCollection, Func<TIn, TOut> toOuter)
    {
        this.getCollection = getCollection ?? throw new ArgumentNullException(nameof(getCollection));
        this.toOuter = toOuter ?? throw new ArgumentNullException(nameof(toOuter));
    }

    protected TCollection Collection { get { return getCollection(); } }
    protected TOut ToOuter(TIn inner) { return toOuter(inner); }
    public abstract void Add(TOut item);
    public abstract void Clear();

    public virtual bool Contains(TOut item)
    {
        var comparer = EqualityComparer<TOut>.Default;
        foreach (var member in Collection)
            if (comparer.Equals(item, ToOuter(member)))
                return true;
        return false;
    }

    public void CopyTo(TOut[] array, int arrayIndex) => this.CopyToArray(array, arrayIndex);
    public int Count { get { return Collection.Count; } }
    public abstract bool IsReadOnly { get; }
    public abstract bool Remove(TOut item);
    public IEnumerator<TOut> GetEnumerator() => Collection.Select(item => ToOuter(item)).GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}

public class CollectionAdapter<TIn, TOut> : CollectionAdapterBase<TIn, TOut, ICollection<TIn>>
{
    readonly Func<TOut, TIn> toInner;

    public CollectionAdapter(Func<ICollection<TIn>> getCollection, Func<TIn, TOut> toOuter, Func<TOut, TIn> toInner)
        : base(getCollection, toOuter)
    {
        this.toInner = toInner ?? throw new ArgumentNullException(nameof(toInner));
    }

    protected TIn ToInner(TOut outer) { return toInner(outer); }
    public override void Add(TOut item) => Collection.Add(ToInner(item));
    public override void Clear() => Collection.Clear();
    public override bool IsReadOnly { get { return Collection.IsReadOnly; } }
    public override bool Remove(TOut item) => Collection.Remove(ToInner(item));
    public override bool Contains(TOut item) => Collection.Contains(ToInner(item));
}

public static class EnumerableExtensions
{
    internal static void CopyToArray<TItem>(this IEnumerable<TItem> collection, TItem[] array, int arrayIndex) 
    {
        ArgumentNullException.ThrowIfNull(collection);  
        ArgumentNullException.ThrowIfNull(array);   
        foreach (var item in collection)
            array[arrayIndex++] = item;
    }
}

然后修改您的类以使用它,如下所示:

public class Sender {
    public string SenderID { get; set; }
    public string FeedType { get; set; }
    
    public IntegerDictionaryAdapter<CategoryMapping> CategoryMappings { get; set; } = new();
}

public class CategoryMapping {
    public int CategoryID { get; set; }
    public string VccCategoryName { get; set; }
    public string ReiCategoryName { get; set; }
    
    public IntegerDictionaryAdapter<CategoryMapping> SubcategoryMappings { get; set; } = new();
}

public class SubcategoryMapping
{
    public int SubcategoryID { get; set; }
    public int ParentCategoryID { get; set; }
    public string VccSubcategoryName { get; set; }
    public string ReiSubcategoryName { get; set; }
}

现在,您将能够在.NET 6(以及.NET 7)中绑定您的配置数据模型,如下所示,使用UnderlyingDictionary属性访问您的整数键词典:

List<Sender> people = Configuration.GetSection("TestMap").Get<List<Sender>>();

people.First().CategoryMappings.UnderlyingDictionary.Add(10101, new CategoryMapping { CategoryID = 10101, VccCategoryName = "foo", ReiCategoryName = "bar" });

(然而,老实说,我不确定是否值得这么麻烦.)

演示小提琴here.

Csharp相关问答推荐

Blazor:子编辑表单上的嵌套编辑表单验证

亚马逊Pinpoint C# SDK

无法使用ternal- .net修复可空警告

C#类主构造函数中的调试参数

数组被内部函数租用时,如何将数组返回给ArrayPool?

System.Text.Json数据化的C#类映射

从应用程序图API调用访问所有者字段

Quartz调度程序不调用作业(job)类

Amazon SP-API确认发货不设置&Quot;递送服务

在实体框架中处理通用实体&S变更跟踪器

反序列化私有成员

DateTime ToString()未以指定格式打印

为值对象编写自定义JsonConverter

在PostgreSQL上使用ExecuteSqlRawAsync的C#11原始字符串文字有区分大小写的问题

如何在.NET Maui中将事件与MVVM一起使用?

为什么当我try 为玩家角色设置动画时,没有从文件夹中拉出正确的图像?

流畅的验证--如何为属性重用规则?

如何在特定时间间隔运行多个后台任务?

游戏对象走向不同的方向

用于分钟和秒验证的MudTextfield的正则表达式掩码