RestSharp:无法将'RestSharp.JsonArray'类型的对象强制转换为'System.Collections.Generic.IDictionary'

时间:2017-10-30 11:27:06

标签: c# deserialization restsharp

到目前为止无法修复问题:无法将类型为'RestSharp.JsonArray'的对象强制转换为'System.Collections.Generic.IDictionary`2 [System.String,System.Object - 我可以看到此错误在这里,在回应中:

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

但是我到达NullReferenceExeption:

var name = response.Data.Name;

这是我的测试类:

    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;

.....

我得到的回复包含这些数据:

[
  {
    "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"
  }
] 

这是我正在尝试反序列化的实现类:

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

我很感谢你的任何帮助,伙计们!

2 个答案:

答案 0 :(得分:4)

您正在返回一个ThirdPartySuggester数组,因此您需要指定一个List:

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

然后要访问它们,请使用循环

foreach (ThirdPartySuggester item in response.Data)
{
  //get each items properties
}

答案 1 :(得分:0)

创建包装类还有另一种方法

public  class ThirdPartySuggesters : List<ThirdPartySuggester> {}
var response = client.Execute<ThirdPartySuggesters>(request);