c# - 如何在 Xamarin 上的 Get API 中将此 JSON 对象映射到 C# 对象
问题描述
我在下面有这个 JSON 对象
{
"Metadata": {
"TotalRecords": 12,
"CurrentPageSize": 2,
"CurrentPage": 1,
"TotalPages": 2
},
"Results": [
{
"Id": 1,
"OwnerId": "3be73a87-a977-467a-84c0",
"OwnerName": "AV",
"CategoryId": 3,
"CategoryName": "User 1 Physical",
"Name": "User 1 Speed",
"Description": null,
"NoOfMinutes": 15,
"CreatedDate": "2019-09-22T03:34:56.4033333",
"ModifiedDate": null
},
{
"Id": 2,
"OwnerId": "3be73a87-a977-467a-84c0",
"OwnerName": "AV",
"CategoryId": 1,
"CategoryName": "User 1 Technique",
"Name": "User 1 tech",
"Description": null,
"NoOfMinutes": 60,
"CreatedDate": "2019-09-22T03:34:56.4033333",
"ModifiedDate": null
}
]
}
并使用 JSON2Csharp:
public class Metadata
{
public int TotalRecords { get; set; }
public int CurrentPageSize { get; set; }
public int CurrentPage { get; set; }
public int TotalPages { get; set; }
}
public class Result
{
public int Id { get; set; }
public string OwnerId { get; set; }
public string OwnerName { get; set; }
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string Name { get; set; }
public object Description { get; set; }
public int NoOfMinutes { get; set; }
public DateTime CreatedDate { get; set; }
public object ModifiedDate { get; set; }
}
public class RootObject
{
public Metadata Metadata { get; set; }
public List<Result> Results { get; set; }
}
如何将整个事情不仅仅是结果(称为活动)映射到 Xamarin API 服务以获取数据并返回?
这是更改整个数据结构之前的原始 API:
public async List<Activities> GetActivities()
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", "ACCCESS TOKEN HERE");
var response = httpClient.GetStringAsync("https://XXX.azurewebsites.net/api/v1/Activities");
JsonConvert.DeserializeObject<Activities>(response);
}
解决方案
你的api的返回对象是什么?如果返回对象的结构是"Metadata":..., "Results":[...]
(你问题中的第一个 json),你需要使用
JsonConvert.DeserializeObject<RootObject>(response);
转换它。
推荐阅读
- sql - 你如何获得按天计算的值的总和,但在 SQL 列中按天计算
- git - 如何在 git pull 具有不同用户和组的文件的目录期间保留用户和组?
- bootstrap-4 - 删除空格引导程序
- java - 使用 Apache Jena 使用 Sparql 查询 JsonLd
- python - 当我运行“flask shell”时,为什么 Python 3 REPL 没有在选项卡上显示方法和属性建议?
- r - R:在数据帧单元格搜索中插入值,从另一个数据帧中提取它
- python - 在python中处理内存不足的终止信号
- c# - Xamarin Forms Tap Gesture Click Effect on Stack 布局
- arrays - Julia,创建 3 的 Int8 数组的简约方法?
- ffmpeg - 我尝试使用 ffmpeg 将屏幕流式传输到多个源并出现错误