首页 > 解决方案 > 如何在 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);
        }

标签: c#jsonxamarin

解决方案


你的api的返回对象是什么?如果返回对象的结构是"Metadata":..., "Results":[...](你问题中的第一个 json),你需要使用

JsonConvert.DeserializeObject<RootObject>(response);

转换它。


推荐阅读