問題描述
我有這個(gè) 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);
但我收到此錯(cuò)誤:
無法將當(dāng)前 JSON 數(shù)組(例如 [1,2,3])反序列化為類型'test.Model.RetrieveMultipleResponse' 因?yàn)樵擃愋托枰?JSON對(duì)象(例如 {"name":"value"})正確反序列化.要解決這個(gè)問題錯(cuò)誤要么將 JSON 更改為 JSON 對(duì)象(例如 {"name":"value"})或?qū)⒎葱蛄谢愋透臑閿?shù)組或?qū)崿F(xiàn)的類型一個(gè)集合接口(例如 ICollection、IList),比如 List 可以從 JSON 數(shù)組反序列化.JsonArrayAttribute 也可以添加到類型以強(qiáng)制它從 JSON 數(shù)組反序列化.小路'',第 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 字符串包含在方括號(hào) ([]
) 中,因此它被解釋為數(shù)組而不是單個(gè) RetrieveMultipleResponse
對(duì)象.因此,您需要將其反序列化為 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);
這篇關(guān)于無法將 JSON 數(shù)組(例如 [1,2,3])反序列化為類型“",因?yàn)轭愋托枰?JSON 對(duì)象(例如 {“name":“value"})才能正確反序列化的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!