'Unable to Deserialize HttpResponseMessage to Model Object

  1. Code for Getting the 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. Model Object:

    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 after I get it in string (string apiResponse = response.Content.ReadAsStringAsync().Result)

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

I have C#.NET service, where I am consuming GitHub APIs. I am able to successfully get the data, but unfortunately in the incorrect format(please check step 3). I am not able to convert the response to my custom object)

Here, the response is JSONarray to be precise.



Solution 1:[1]

Based on your Json results, it seems your model object needs to be something like this:

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; }
}

Also I would strongly recommend you to use the await keyword instead of Result:

string apiResponse = await response.Content.ReadAsStringAsync();

Solution 2:[2]

Use your custom class at object type

var jsonString = responseMessage.Content.ReadAsStringAsync().Result;
var myObject = JsonConvert.DeserializeObject<object>(jsonString);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 GeralexGR