gpt4 book ai didi

c# - 使用 JsonConverter 反序列化 JSON 字典值

转载 作者:行者123 更新时间:2023-11-30 23:33:56 34 4
gpt4 key购买 nike

我使用 Json.NET 库反序列化 JSON。对于抽象类 Foo,我有一个自定义的 JsonConverter。这是我使用它的方式:

[JsonConverter(typeof(FooJsonConverter))]
public Foo MyFoo { get; set; }

到目前为止一切顺利。当我在字典中使用 Foo 类时,问题就出现了。这是我的尝试:

[JsonDictionary(ItemConverterType = typeof(FooJsonConverter))]
public Dictionary<string, Foo> MyFooDictionary { get; set; }

但是上面给出了错误:

Attribute 'JsonDictionary' is not valid on this declaration type. It is only valid on 'class, interface' declarations.

如何为字典值指定转换器?

最佳答案

使用 [JsonProperty] 而不是 [JsonDictionary]

[JsonProperty(ItemConverterType = typeof(FooJsonConverter))]
public Dictionary<string, Foo> MyFooDictionary { get; set; }

fiddle :https://dotnetfiddle.net/QJCtBg

另一种方法是将您的转换器添加到 JsonSerializerSettings 并将其传递给 JsonConvert.DeserializeObject

var settings = new JsonSerializerSettings();
settings.Converters.Add(new FooJsonConverter());

var obj = JsonConvert.DeserializeObject<ObjType>(json, settings);

关于c# - 使用 JsonConverter 反序列化 JSON 字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33674734/

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