Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestSharp: Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`

Can't fix an issue so far: Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object -- this error I can see here, in the response itself:

var response = client.Execute<ThirdPartySuggester>(request);

but the NullReferenceExeption I get here:

var name = response.Data.Name;

This is my test class:

    public class Class1
    {
        [Theory]
        [InlineData("apple", "en-us")]
        public void SearchTest(string searchPhrase, string language)
        {
            var client = new RestClient("https://test_site/api");
            var request = new RestRequest("/thirdparty/suggester?searchPhrase={search_key}&marketLocale={language_id}", Method.GET);
            request
                .AddUrlSegment("search_key", searchPhrase)
                .AddUrlSegment("language_id", language);
            var response = client.Execute<ThirdPartySuggester>(request);

            var name = response.Data.Name;
            var manufacturer = response.Data.Manufacturer;
            var deviceType = response.Data.DeviceType;
            var searchKey = response.Data.SearchKey;

.....

The response I get contains this data:

[
  {
    "name": "iPhone 7 Plus",
    "manufacturer": "Apple",
    "deviceType": "smartphone_tablet",
    "searchKey": "apple_iphone_7_plus"
  },
  {
    "name": "iPhone 4s",
    "manufacturer": "Apple",
    "deviceType": "smartphone_tablet",
    "searchKey": "apple_iphone_4s"
  },
  {
    "name": "iPhone 6",
    "manufacturer": "Apple",
    "deviceType": "smartphone_tablet",
    "searchKey": "apple_iphone_6"
  },
  {
    "name": "iPod Touch 8th Generation",
    "manufacturer": "Apple",
    "deviceType": "smartphone_tablet",
    "searchKey": "apple_ipod_touch_8th_generation"
  },
  {
    "name": "iPhone 7",
    "manufacturer": "Apple",
    "deviceType": "smartphone_tablet",
    "searchKey": "apple_iphone_7"
  }
] 

Here is an implementation class of what I'm trying to deserialize:

public class ThirdPartySuggester
{
    public string Name { get; set; }
    public string Manufacturer { get; set; }
    public string DeviceType { get; set; }
    public string SearchKey { get; set; }
}

I would appreciate any help from you, guys!

like image 947
SerjK Avatar asked Oct 30 '17 11:10

SerjK


1 Answers

You're getting an array of ThirdPartySuggester returned, so you need to specify a List :

var response = client.Execute<List<ThirdPartySuggester>>(request);

Then to access them, use a loop

foreach (ThirdPartySuggester item in response.Data)
{
  //get each items properties
}
like image 185
Riv Avatar answered Oct 07 '22 19:10

Riv