代码之家  ›  专栏  ›  技术社区  ›  SerjK

RestSharp:无法强制转换“RestSharp”类型的对象。JsonArray“to type”系统。收藏。通用的I词典`

  •  6
  • SerjK  · 技术社区  · 7 年前

    目前无法修复问题:无法强制转换“RestSharp”类型的对象。JsonArray“to type”系统。收藏。通用的IDictionary'2[System.String,System.Object--我可以在响应本身中看到这个错误:

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

    但是我在这里得到的NullReferenceExection:

    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 回复  |  直到 7 年前
        1
  •  18
  •   Riv    7 年前

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

    然后使用循环访问它们

    foreach (ThirdPartySuggester item in response.Data)
    {
      //get each items properties
    }
    
        2
  •  0
  •   binhtruong.it    4 年前

    还有一种方法是创建wrap类

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