c# - 无法将 HttpResponseMessage 反序列化为模型对象
问题描述
获取代码
Response
:public async Task<List<RepositoryListResponseItem>> MakeGitRequestAsync<T>(string url) { List<RepositoryListResponseItem> res = new List<RepositoryListResponseItem>(); using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json"); httpClient.DefaultRequestHeaders.Add("User-Agent", "HttpFactoryTesting"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); using (HttpResponseMessage response = await httpClient.GetAsync(url)) { if (response.IsSuccessStatusCode == true) { string apiResponse = response.Content.ReadAsStringAsync().Result; res = JsonConvert.DeserializeObject<List<RepositoryListResponseItem>>(apiResponse); } } } return res; }
模型对象:
public class RepositoryListResponseItem { [Description("Repo Name")] [JsonPropertyName("full_name")] public string RepoName { get; set; } [Description("Repo Link")] [JsonPropertyName("html_url")] public string RepoLink { get; set; } }
HttpWebResponse 在我得到它之后的字符串(
string apiResponse = response.Content.ReadAsStringAsync().Result
)[{\"id\":114995175,\"node_id\":\"MDEwOlJlcG9zaXRvcnkxMTQ5OTUxNzU=\",\"name\":\"AlcoholConsumption\",\"full_name\":\"ihri/AlcoholConsumption\",\....
我有 C#.NET 服务,我正在使用 GitHub API。我能够成功获取数据,但不幸的是格式不正确(请检查步骤 3)。我无法将响应转换为我的自定义对象)
在这里,响应是JSONarray
准确的。
解决方案
根据您的Json
结果,您的模型对象似乎需要是这样的:
public class RepositoryListResponseItem
{
public int id { get; set; }
public string node_id { get; set; }
public string name { get; set; }
public string full_name { get; set; }
}
另外我强烈建议您使用await
关键字而不是Result
:
string apiResponse = await response.Content.ReadAsStringAsync();
推荐阅读
- reactjs - Promise.then 没有按预期工作
- windows - pipenv 在安装依赖项时找不到模块“runpy”
- glsl - 如何确定 WebGL 和 GLSL 版本?
- apache-kafka - 为什么Kafka connect轻量级?
- android - 飞溅后未显示主要活动
- c++ - 类成员参数中的 Consexpr
- linux - 符号链接编辑和硬链接的差异
- amazon-web-services - ACM 证书 - SSL_ERROR_BAD_CERT_DOMAIN
- reactjs - 反应:在父重新渲染时,道具不会传递给子组件
- azure-functions - Azure 函数存储帐户