C#如何创建可处理响应自定义数据类型的JSON泛型基类
实现步骤
1. 定义通用泛型响应基类
把所有接口返回的公共字段抽离为泛型类,T 对应response字段的具体类型:
using Newtonsoft.Json; namespace FootballAPI.Models { // 通用API响应基类 public class ApiResponse<T> { [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 T Response { get; set; } } // 公共分页类,所有接口复用 public class Paging { [JsonProperty("current")] public long Current { get; set; } [JsonProperty("total")] public long Total { get; set; } } }
2. 调整Country类适配序列化
因为JSON返回的属性名是小写开头,显式加JsonProperty映射避免大小写匹配问题:
using Newtonsoft.Json; public class Country { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("code")] public string Code { get; set; } [JsonProperty("flag")] public string Flag { get; set; } }
3. 反序列化使用示例
/countries接口的response是数组结构,泛型参数指定为Country[]即可:
// jsonString为接口返回的完整响应字符串 var result = JsonConvert.DeserializeObject<ApiResponse<Country[]>>(jsonString); // 取值示例 Country[] countryList = result.Response; long totalCountryCount = result.Results; long currentPage = result.Paging.Current;
4. 其他接口复用规则
后续其他接口只需要定义对应response的实体类,替换泛型参数即可,比如获取球员的接口response是Player数组,写法为:
var playerResult = JsonConvert.DeserializeObject<ApiResponse<Player[]>>(playerResponseJson);
内容的提问来源于stack exchange,提问作者sfarzoso
相关产品推荐
相关产品推荐

