gpt4 book ai didi

c# - .Net 6使用选项模式读取以int为键的json文件

转载 作者:行者123 更新时间:2023-12-03 07:50:44 25 4
gpt4 key购买 nike

我正在尝试使用 C# 选项模式读取 json 文件。但是,我遇到了一个问题,即 Dictionary 的属性未正确映射,除非我将其 key 更改为像 Dictionary

这样的字符串

这是我的示例 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>>();

问题::在我当前的模型中,变量“People”的 CategoryMapping 将为 null,但会正确检索其他信息,例如 SenderID 或 FeedType。

但是,如果我将“CategoryingMappings”更改为 Dictionary<string, CategoryMapping> ,那么它将被正确映射。 CategoryMapping 类的“SubcategoryMapping”属性也发生了同样的情况。

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

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) {
}
}

我需要帮助:将 json 读入我的类对象时,我想要整数作为键。我如何实现这一目标?

最佳答案

你的问题是Microsoft.Extensions.Configuration.Binder 不使用 System.Text.Json 反序列化 JSON。相反,它手动将 JSON 解析为 IConfigurationSection然后,元素使用反射将它们绑定(bind)到 POCO。这些似乎都没有记录,因此为了确认,您可以检查 source code for ConfigurationBinder .

.NET 6 ,方法BindDictionary()用于绑定(bind)到字典。它对字典键类型有注释限制为 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另一种方法BindDictionaryInterface()存在其中包含显式支持数字键的逻辑(通过 PR #71609 添加):

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;
}

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

如果您无法迁移到 .NET 7,但仍需要使用带有整数键的字典,那么作为解决方法,您可以使用 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; }
}

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

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

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

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

演示 fiddle here .

关于c# - .Net 6使用选项模式读取以int为键的json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77175066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com