c# - 如何创建一个基本 JSON 模式类来处理自定义数据类型作为响应?
问题描述
我正在创建一个库包装器来处理这个足球网站API
的所有请求。当我调用端点时,会返回此响应结构:
{
"get": "countries",
"parameters": [],
"errors": [],
"results": 161,
"paging": {
"current": 1,
"total": 1
},
"response": [
{
"name": "Albania",
"code": "AL",
"flag": "https://media.api-sports.io/flags/al.svg"
},
{
"name": "Algeria",
"code": "DZ",
"flag": "https://media.api-sports.io/flags/dz.svg"
},
{
"name": "Andorra",
"code": "AD",
"flag": "https://media.api-sports.io/flags/ad.svg"
},
]
}
上面的示例是/countries
端点。我使用Quicktype来生成模式结构,我得到了这个:
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace FootballAPI.Models
{
public partial class Temperatures
{
[JsonProperty("get")]
public string Get { get; set; }
[JsonProperty("parameters")]
public object[] Parameters { get; set; }
[JsonProperty("errors")]
public object[] Errors { get; set; }
[JsonProperty("results")]
public long Results { get; set; }
[JsonProperty("paging")]
public Paging Paging { get; set; }
[JsonProperty("response")]
public Response[] Response { get; set; }
}
public partial class Paging
{
[JsonProperty("current")]
public long Current { get; set; }
[JsonProperty("total")]
public long Total { get; set; }
}
public partial class Response
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("flag")]
public Uri Flag { get; set; }
}
}
我想要做的是有一个基本结构模式,其中包含除response
属性之外的所有内容。在上面的例子response
中必须是一个实例,Country
它是:
public class Country
{
public string name { get; set; }
public string code { get; set; }
public string flag { get; set; }
}
我怎样才能告诉上面的基本模式Country
用作T
对象?我应该能够正确解析所有内容Newtonsoft.JSON
:
JsonConvert.DeserializeObject<Country>;
在这种情况下,我有不同的方法,比如GetCountries()
只传递查询字符串/countries
。所以我知道当时我期望的具体类型"response"
。
解决方案
试试这些课程
public class Country
{
public string name { get; set; }
public string code { get; set; }
public string flag { get; set; }
}
public class Countries
{
public string get { get; set; }
public List<object> parameters { get; set; }
public List<object> errors { get; set; }
public int results { get; set; }
public Paging paging { get; set; }
public List<Country> response { get; set; }
}
public class Paging
{
public int current { get; set; }
public int total { get; set; }
}
您可以使用
JsonConvert.DeserializeObject<Countries>(json);
推荐阅读
- ruby - 遍历数组并在 Ruby 中的一行中初始化多个变量
- java - Java Discord API 加入事件
- jquery - 从 JQuery 错误中获取 responseText 错误值?
- c++ - CMake不合逻辑的路径解析?
- javascript - 如何停止计时器计数并从节省的时间开始
- microsoft-graph-api - 过滤最近的文件 Microsoft Graph API 不起作用
- python - Python - Pandas - SQL 查询参数 - 无法过滤没有双引号的数据
- python - 拆分python模块而不重构所有用法
- cypress - Cypress.exec 调用外部脚本并设置环境变量
- python - 将 scipy 结果转换为字典的通用方法