0

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?

KDev
  • 137
  • 10
  • Please show code that attempts to deserialize into `MySimpleClassWithAnArray` and include the specific error message. – Noah Stahl Aug 09 '21 at 12:44
  • how does string array appear when you use it in the browser? Whatever works there you should be able to replicate when building your request url in code – Jason Aug 09 '21 at 12:45
  • Hi @Jason, in JSON format this would be something like { "searchKeys" : ["text1", "text2"] } – KDev Aug 10 '21 at 10:46
  • Hi @NoahStahl, the error message is "Unexpected character encountered while parsing value: [. Path 'searchKeys', line (line no.), position (position no.)' – KDev Aug 10 '21 at 10:48
  • That's not what I asked. A GET is just a normal browser request. What querystring would you use in a browser to pass your array to the server? Whatever you do in the browser you would replicate in your code. – Jason Aug 10 '21 at 10:50
  • Ah yes apologies @Jason, here is what works in the browser: "mywebsite/myAPI/v1/groups?searchKeys=text1,text2". That however is not how I want to use it, I would like to pass the searchKeys text as part of the JSON body. – KDev Aug 10 '21 at 11:08
  • if you want to pass a JSON body, use POST. That's not how GET works. – Jason Aug 10 '21 at 11:12
  • @Jason I am interfacing to a Wordpress BuddyPress API to perform a GET request. It accepts a JSON body as part of the request. But that is a moot point, this is an absolutely valid method to perform a GET request. My function works fine, I just want to make it cater for arrays. – KDev Aug 10 '21 at 11:22
  • Hi @KDev, have you checked this thread: https://stackoverflow.com/questions/9981330/pass-an-array-of-integers-to-asp-net-web-api ? – Jessie Zhang -MSFT Aug 11 '21 at 08:40

1 Answers1

0

In order for Deserialize to work, The class shall be as below.

public class MySimpleClassWithAnArray
 {
     public int page { get; set; } = 1;
     public SearchKeys SearchKeys { get; set; }   // modify this line
 }
 
 public class SearchKeys   // add this class
 {
     public string[] Keys {get;set;}
 }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Ajeet Kumar
  • 687
  • 6
  • 12
  • Thanks, I tried this however the parsing still fails with a slightly different error to before: "Unexpected character encountered while parsing value: {. Path 'searchKeys', line (line no.), position (position no.)" – KDev Aug 10 '21 at 11:03
  • As per the error, it seems that either its not a valid json or the model is not correct – Ajeet Kumar Aug 10 '21 at 11:23
  • Check this [link](https://stackoverflow.com/questions/23259173/unexpected-character-encountered-while-parsing-value) – Ajeet Kumar Aug 10 '21 at 11:25
  • Hmm well I suspect it has more to do with with this line "var query = JsonConvert.DeserializeObject>(data);". Because I want to split the object from a class to a parameterized query to place into the request, it works fine for non-array field since the JSON deserialize is able to convert it, but it is not able to convert an array (or a class, like you described in your answer). – KDev Aug 10 '21 at 11:33