I've created the following function to send an object via a HTTP GET request.
public async Task<string> Get<T>(T item, string path, string authorisationToken = "")
{
var data = JsonConvert.SerializeObject(item);
var query = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (!string.IsNullOrWhiteSpace(authorisationToken))
{
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", authorisationToken);
}
HttpResponseMessage response = await httpClient.GetAsync(QueryHelpers.AddQueryString(path, query));
HttpContent Content = response.Content;
var json = await Content.ReadAsStringAsync();
response.Dispose();
return json;
}
While this works great for sending basic classes, it falls over if the class has anything like an array.
For example, sending instances of this class works fine;
public class MySimpleClassWithNoArray
{
public int page { get; set; } = 1;
public string searchKey { get; set; } = string.Empty;
}
But trying to send an instance of this class falls over because the JsonConvert.DeserializeObject function fails;
public class MySimpleClassWithAnArray
{
public int page { get; set; } = 1;
public string searchKeys[] { get; set; }
}
How can I improve on this function to cater for arrays and possibly other types?