無法將JSON數組(例如[1,2,3])反序列化為類型''因為類型需要JSON對象(例如{“name”:“value”})才能正確反序列化我有這個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"
}]但我收到這個錯誤:無法將當前JSON數組(例如[1,2,3])反序列化為類型'test.Model.RetrieveMultipleResponse',因為該類型需要JSON對象(例如{“name”:“value”})才能正確反序列化。要修復此錯誤,請將JSON更改為JSON對象(例如{“name”:“value”})或將反序列化類型更改為數組或實現集合接口的類型(例如ICollection,IList),例如List從JSON數組反序列化。JsonArrayAttribute也可以添加到類型中以強制它從JSON數組反序列化。路徑'',第1行,第1位。
3 回答

米琪卡哇伊
TA貢獻1998條經驗 獲得超6個贊
您的json字符串包含在方括號([]
)中,因此它被解釋為數組而不是單個RetrieveMultipleResponse
對象。因此,您需要將其反序列化為類型集合RetrieveMultipleResponse
,例如:
var objResponse1 = JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);

慕森王
TA貢獻1777條經驗 獲得超3個贊
如果一個人想支持泛型(在擴展方法中)這就是模式......
public static List<T> Deserialize<T>(this string SerializedJSONString){ var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString); return stuff;}
它是這樣使用的:
var rc = new MyHttpClient(URL);//This response is the JSON Array (see posts above)var response = rc.SendRequest();var data = response.Deserialize<MyClassType>();
MyClassType看起來像這樣(必須匹配JSON數組的名稱值對)
[JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class MyClassType { [JsonProperty(PropertyName = "Id")] public string Id { get; set; } [JsonProperty(PropertyName = "Name")] public string Name { get; set; } [JsonProperty(PropertyName = "Description")] public string Description { get; set; } [JsonProperty(PropertyName = "Manager")] public string Manager { get; set; } [JsonProperty(PropertyName = "LastUpdate")] public DateTime LastUpdate { get; set; } }
使用NUGET下載Newtonsoft.Json在需要的地方添加引用...
using Newtonsoft.Json;

繁花不似錦
TA貢獻1851條經驗 獲得超4個贊
無法在解決方案中添加注釋,但這對我不起作用。對我有用的解決方案是使用:
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); return des.data.Count.ToString();
添加回答
舉報
0/150
提交
取消