【发布时间】:2020-02-11 09:08:07
【问题描述】:
我正在尝试将此 json 数组转换为在列表视图中显示数据。但是我在解析这个时遇到了这个错误。
无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[Apps.Models.RootObject]”,因为该类型需要 JSON 数组(例如[1,2,3]) 正确反序列化。 要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径“id”,第 1 行,位置 6。
JSON 文件如下所示:
{
"id": 2,
"parent_id": 1,
"name": "Default Category",
"is_active": true,
"position": 1,
"level": 1,
"product_count": 4503,
"children_data": [
{
"id": 848,
"parent_id": 2,
"name": "GROCERIES",
"is_active": true,
"position": 0,
"level": 2,
"product_count": 198,
"children_data": [
{
"id": 849,
"parent_id": 848,
"name": "SUGAR",
"is_active": true,
"position": 0,
"level": 3,
"product_count": 13,
"children_data": [
{
"id": 850,
"parent_id": 849,
"name": "RING",
"is_active": true,
"position": 0,
"level": 4,
"product_count": 3,
"children_data": []
}
]
},
{
"id": 851,
"parent_id": 848,
"name": "RICE",
"is_active": true,
"position": 0,
"level": 3,
"product_count": 47,
"children_data": [
{
"id": 852,
"parent_id": 851,
"name": "RING",
"is_active": true,
"position": 0,
"level": 4,
"product_count": 1,
"children_data": []
}
]
}
]
},
{
"id": 2017,
"parent_id": 2,
"name": "Food Basket",
"is_active": true,
"position": 2,
"level": 2,
"product_count": 19,
"children_data": []
}
]}
我的模型类是: 我创建了一个这样的模型类。
public class ChildrenData2
{
public string id { get; set; }
public string parent_id { get; set; }
public string name { get; set; }
public string is_active { get; set; }
public string position { get; set; }
public string level { get; set; }
public string product_count { get; set; }
public List children_data { get; set; }
}
public class ChildrenData
{
public ChildrenData2 children_data { get; set; }
}
public class RootObject
{
public List<ChildrenData> children_data { get; set; }
}
JSON 反序列化代码: 我正在尝试这段代码来解析 json 数组。
var client = new System.Net.Http.HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
Constants.AccessName, Constants.AccessToken);
var json = await client.GetAsync(Constants.BaseApiAddress + "V1/categories");
string contactsJson = await json.Content.ReadAsStringAsync();
if (contactsJson != "")
{
//Converting JSON Array Objects into generic list
Newtempdata = JsonConvert.DeserializeObject<List<RootObject>>(contactsJson);
}
【问题讨论】:
-
你可以复制你的JSON并在VS中使用
Edit => Paste Special => Paste JSON as Classes。
标签: c# xamarin.forms