指定的强制转换在HttpClient请求中无效

时间:2017-10-11 10:43:29

标签: c# json httpclient

我正在使用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;
            }


        }

2 个答案:

答案 0 :(得分:1)

您正试图在此行上反序列化为字典:

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

尝试使用您创建的课程:

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

答案 1 :(得分:0)

基于JSON对类进行建模可能会有问题。确保您的模型类完全符合您的JSON,并检查相应的数据类型。

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