无法反序列化HttpResponseMessage到模型对象

时间:2020-04-07 08:23:53

标签: c# json asp.net-core json-deserialization

  1. 获取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;
    }
    
  2. 模型对象:

    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; }
    }
    
    1. 我在字符串(string apiResponse = response.Content.ReadAsStringAsync().Result)中获得HttpWebResponse

      [{\"id\":114995175,\"node_id\":\"MDEwOlJlcG9zaXRvcnkxMTQ5OTUxNzU=\",\"name\":\"AlcoholConsumption\",\"full_name\":\"ihri/AlcoholConsumption\",\....
      

我有C#.NET服务,正在使用GitHub API。我能够成功获取数据,但不幸的是格式错误(请检查步骤3)。 我无法将响应转换为我的自定义对象)

在这里,准确的说是JSONarray

1 个答案:

答案 0 :(得分:0)

根据您的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();