【问题标题】:Specified cast is not valid in HttpClient request指定的强制转换在 HttpClient 请求中无效
【发布时间】:2017-10-11 10:43:28
【问题描述】:

我正在使用 xamarin.forms 开发一个应用程序,当执行 GET 请求以在视图中显示 CompanyName 和 CompanyLogo 时,它会引发以下异常:异常: System.InvalidCastException:指定的强制转换无效。发生。任何有关如何解决此问题的帮助将不胜感激。谢谢。下面是我的代码。

我的 Json 响应:

{
    "Credentials": {
        "Token": "K6Zi8VXfqWuthxgn3YEfrU6Bj/EKM7BqvSZcatFgvMx408yadbE+Qj6IuTnZ++C9q4Ty1W2f1quNYMKZxFBNZg==",
        "Authenticated": true,
        "SecretKey": null
    },
    "Companies": [
        {
            "CustomerID": 2,
            "CompanyName": "Posworx",
            "CompanyLogo": "\\admin.loyaltyworx.co.za\\Images\\LOYALTY-LW.png",
            "Stores": [
                {
                    "StoreID": 2,
                    "StoreNumber": null,
                    "StoreName": "Pos Store",
                    "StoreAddress": "218 Stamford Hill Road",
                    "StoreCity": "Durban",
                    "StoreRegion": "KZN",
                    "StoreCountry": "South Africa"
                },
                {
                    "StoreID": 4,
                    "StoreNumber": null,
                    "StoreName": "Pos Store",
                    "StoreAddress": "218 Mathews Meyiwa Road",
                    "StoreCity": "Durban",
                    "StoreRegion": "KZN",
                    "StoreCountry": "South Africa"
                },
                {
                    "StoreID": 3021,
                    "StoreNumber": null,
                    "StoreName": "Tes tStore",
                    "StoreAddress": "",
                    "StoreCity": "",
                    "StoreRegion": "",
                    "StoreCountry": ""
                },
                {
                    "StoreID": 3061,
                    "StoreNumber": null,
                    "StoreName": "tEST",
                    "StoreAddress": "",
                    "StoreCity": "Durban",
                    "StoreRegion": "",
                    "StoreCountry": ""
                }

            ]
        }
    ],
    "IsError": false,
    "ErrorMessage": null
}

班级:

public class Store
        {
            public class Credentials
            {
                public string Token { get; set; }
                public bool Authenticated { get; set; }
                public object SecretKey { get; set; }
            }

            public class StoreDetails
            {
                public int StoreID { get; set; }
                public object StoreNumber { get; set; }
                public string StoreName { get; set; }
                public string StoreAddress { get; set; }
                public string StoreCity { get; set; }
                public string StoreRegion { get; set; }
                public string StoreCountry { get; set; }
            }

            public class Company
            {
                public int CustomerID { get; set; }
                public string CompanyName { get; set; }
                public string CompanyLogo { get; set; }
                public IList<Store> Stores { get; set; }
            }

            public class Stores
            {
                public Credentials Credentials { get; set; }
                public IList<Company> Companies { get; set; }
                public bool IsError { get; set; }
                public object ErrorMessage { get; set; }
            }
        }

请求:

public async void LoadData()
        {
            Store.Stores store = new Store.Stores();
            try
            {
                var content = "";
                HttpClient client = new HttpClient();
                var RestUrl = "/api/Company/GetCustomerCompanies";
                client.BaseAddress = new Uri(RestUrl);

                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("X-Giftworx-App", "K6Zi8VXfqWuthxgn3YEfrU6Bj/EKM7BqvSZcatFgvMx408yadbE+Qj6IuTnZ++C9q4Ty1W2f1quNYMKZxFBNZg==");
                HttpResponseMessage response = await client.GetAsync(RestUrl);
                content = await response.Content.ReadAsStringAsync();

                JObject jsonResponse = JObject.Parse(content);
                JObject objResponse = (JObject)jsonResponse["Companies"];
                Dictionary<string, JArray> Items = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, JArray>>(objResponse.ToString());


                MainListView.ItemsSource = Items.ToList();
            }
            catch(Exception ex)
            {
                string exception = ex.Message;
            }


        }

【问题讨论】:

  • 异步方法不应返回 void。你不能等待它们,因此你不能处理异常。另外,你为什么不直接反序列化到Store

标签: c# json httpclient


【解决方案1】:

你正试图反序列化成这一行的字典:

Dictionary<string, JArray> Items = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, JArray>>(objResponse.ToString()); 

尝试使用您创建的类:

var Items = Newtonsoft.Json.JsonConvert.DeserializeObject<Stores>(content);

【讨论】:

  • 应该是 DeserializeObject
  • 已更正。谢谢。
【解决方案2】:

基于 JSON 对类进行建模可能会出现问题。确保您的模型类与您的 JSON 完全一致,并检查相应的数据类型。

这是一个基于 JSON 字符串创建 C# 类的链接: http://json2csharp.com/

【讨论】:

  • 除此之外,在 Visual Studio 中,您可以简单地将 JSON 复制到剪贴板并转到编辑 > 选择性粘贴 > 将 JSON 粘贴为类
猜你喜欢
  • 1970-01-01
  • 2018-05-27
  • 2014-07-30
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多