我正在尝试转换此json数组以在列表视图中显示数据。但是当我解析这个时,我收到这个错误。
无法将当前 JSON 对象(例如{"name":"value"}(反序列化为类型"System.Collections.Generic.List'1[Apps.Models.RootObject]",因为该类型需要一个 JSON 数组(例如 [1,2,3](才能正确反序列化。 若要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3](或更改反序列化类型,使其是可以从 JSON 对象反序列化的普通 .NET 类型(例如,不是整数等基元类型,也不是数组或列表等集合类型(。还可以将 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,您的模型将如下所示
public class ChildrenData
{
public int id { get; set; }
public int parent_id { get; set; }
public string name { get; set; }
public bool is_active { get; set; }
public int position { get; set; }
public int level { get; set; }
public int product_count { get; set; }
public List<ChildrenData> children_data { get; set; }
}
然后,您可以使用JsonConvert
将 JSON 转换为对象。还要记住,这不是List<ChildrenData>
var test = JsonConvert.DeserializeObject<ChildrenData>(json);
使用以下站点创建模型类
http://json2csharp.com/
然后使用 Json反序列化转换模型中的响应
变量结果=JsonConvert.DeserializeObject<typeOfModel>(json);