問題描述
我有這個 JSON:
[
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 1",
"Values": [
"Acc 1"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "1",
"Values": [
"1"
]
}
}
],
"Name": "account",
"Id": "1"
},
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 2",
"Values": [
"Acc 2"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "2",
"Values": [
"2"
]
}
}
],
"Name": "account",
"Id": "2"
},
{
"Attributes": [
{
"Key": "Name",
"Value": {
"Value": "Acc 3",
"Values": [
"Acc 3"
]
}
},
{
"Key": "Id",
"Value": {
"Value": "3",
"Values": [
"3"
]
}
}
],
"Name": "account",
"Id": "2"
}
]
我有這些課程:
public class RetrieveMultipleResponse
{
public List<Attribute> Attributes { get; set; }
public string Name { get; set; }
public string Id { get; set; }
}
public class Value
{
[JsonProperty("Value")]
public string value { get; set; }
public List<string> Values { get; set; }
}
public class Attribute
{
public string Key { get; set; }
public Value Value { get; set; }
}
我正在嘗試使用以下代碼反序列化上述 JSON:
I am trying to deserialize the above JSON using the code below:
var objResponse1 = JsonConvert.DeserializeObject<RetrieveMultipleResponse>(JsonStr);
但我收到此錯誤:
無法將當前 JSON 數組(例如 [1,2,3])反序列化為類型'test.Model.RetrieveMultipleResponse' 因為該類型需要 JSON對象(例如 {"name":"value"})正確反序列化.要解決這個問題錯誤要么將 JSON 更改為 JSON 對象(例如 {"name":"value"})或將反序列化類型更改為數組或實現的類型一個集合接口(例如 ICollection、IList),比如 List 可以從 JSON 數組反序列化.JsonArrayAttribute 也可以添加到類型以強制它從 JSON 數組反序列化.小路'',第 1 行,位置 1.
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'test.Model.RetrieveMultipleResponse' 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 '', line 1, position 1.
推薦答案
您的 json 字符串包含在方括號 ([]
) 中,因此它被解釋為數組而不是單個 RetrieveMultipleResponse
對象.因此,您需要將其反序列化為 RetrieveMultipleResponse
的類型集合,例如:
Your json string is wrapped within square brackets ([]
), hence it is interpreted as array instead of single RetrieveMultipleResponse
object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse
, for example :
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
這篇關于無法將 JSON 數組(例如 [1,2,3])反序列化為類型“",因為類型需要 JSON 對象(例如 {“name":“value"})才能正確反序列化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!