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;
}
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; }
}
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.
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();