c# - 如何使用 Xamarin 表单反序列化 JSON 对象数组
问题描述
我正在尝试将此 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);
}
解决方案
使用以下站点创建模型类
然后使用 JsonDeserialize 转换模型中的响应
变量结果=JsonConvert.DeserializeObject<typeOfModel>(json);
推荐阅读
- android - 什么是 Android 中的“HAL 远程处理”?
- r - 如何在 R 的 GAM 回归中绘制拟合曲线?
- python - 通过 Python-Selenium Web Driver 抓取 Quora 上某个问题下发布的答案的永久链接
- java - 在 Java 中实现 RTSP 服务器以在 VLC 媒体播放器上流式传输视频
- javascript - 当模式中的验证匹配 false 时,Mongoose 不会抛出错误
- pandas - 计算 pandas 中的 groupby (几列)平均值
- c# - 我如何检查子字符串是否包含另一个子字符串 c#
- html - 单击时汉堡菜单不起作用
- python - SQLAlchemy 监听多对多关系中的属性变化并改变发起者的其他属性
- python - 如何在 python 中的 selenium chrome web 驱动程序中获取状态码