【问题标题】:Unable to Deserialize HttpResponseMessage to Model Object无法将 HttpResponseMessage 反序列化为模型对象
【发布时间】:2020-04-07 08:23:53
【问题描述】:
  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. 我得到字符串后的 HttpWebResponse (string apiResponse = response.Content.ReadAsStringAsync().Result)

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

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

这里,准确地说是JSONarray

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 那行得通。我想知道我是否可以将这种方法用于泛型类型说 T?
    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 2021-02-17
    • 2022-12-09
    相关资源
    最近更新 更多