gpt4 book ai didi

c# - 无法将当前 JSON 数组(例如 [1,2,3])反序列化为“System.Collections.Generic.Dictionary”类型

转载 作者:行者123 更新时间:2023-11-30 18:13:21 26 4
gpt4 key购买 nike

我有第三方提供的以下 JSON 格式:

{
"data": {
"objects": {
"0ea73fa9333a7cbeb2d8c69a14b9970f": {
"Id": "0ea73fa9333a7cbeb2d8c69a14b9970f",
"Name": "test"
},
"38b1390ff6bc8a9837105d181000bcc8": {
"Id": "38b1390ff6bc8a9837105d181000bcc8",
"Name": "test"
}
}
}}

我正在使用这个模型反序列化:

public class ObjectTypes
{
public ObjectTypeList data { get; set; }

public class ObjectTypeList
{
public Dictionary<string, Object> objects { get; set; }
}

public class Object
{
public string Id { get; set; }
public string Name { get; set; }
}
}

这工作正常,但有时 JSON 是空的,如下所示:

{
"data": {
"objects": []
}
}

导致此异常的结果:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,Models.ObjectTypes+Object]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path 'data.objects', line 1, position 20.

关于如何解决这个问题有什么建议吗?

最佳答案

您应该反序列化 ObjectTypes

类型
        public partial class ObjectTypes
{
[JsonProperty("data")]
public Data Data { get; set; }
}

public partial class Data
{
[JsonProperty("objects")]
public Dictionary<string, Object> Objects { get; set; }
}

public partial class Object
{
[JsonProperty("Id")]
public string Id { get; set; }

[JsonProperty("Name")]
public string Name { get; set; }
}

关于c# - 无法将当前 JSON 数组(例如 [1,2,3])反序列化为“System.Collections.Generic.Dictionary”类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52835302/

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