【发布时间】:2017-10-04 09:31:12
【问题描述】:
我在我的 Xamarin.forms 应用程序中发出 Api 请求,该请求是显示商店列表,但它引发以下异常: 无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[LoyaltyWorx.Page1+Store]”,因为该类型需要 JSON 数组(例如 [1, 2,3]) 正确反序列化。
Json 响应:
{
"Credentials": {
"Token": "K6Zi8VXfqWuthxgn3YEfrU6Bj/EKM7BqvSZcatFgvMx408yadbE+Qj6IuTnZ++C9q4Ty1W2f1quNYMKZxFBNZg==",
"Authenticated": true,
"SecretKey": null
},
"Companies": [
{
"CustomerID": 2,
"CompanyName": "Posworx",
"CompanyLogo": "\Images\\Capture.JPG",
"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"
}
]
},
Xamarin.Forms 中的类:
public class Store
{
public List<Company> companies { get; set; }
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 Credentials
{
public string Token { get; set; }
public bool Authenticated { get; set; }
public object SecretKey { 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()
{
try
{
var content = "";
HttpClient client = new HttpClient();
var RestUrl = "/api/Company/GetCustomerCompanies";
client.BaseAddress = new Uri(RestUrl);
client.DefaultRequestHeaders.Add("X-Giftworx-App", "K6Zi8VXfqWuthxgn3YEfrU6Bj/EKM7BqvSZcatFgvMx408yadbE+Qj6IuTnZ++C9q4Ty1W2f1quNYMKZxFBNZg==");
HttpResponseMessage response = await client.GetAsync(RestUrl);
content = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<List<Store>>(content);
MainListView.ItemsSource = Items;
}
catch (Exception ex)
{
string exception = ex.Message;
}
}
目标是在 ListView 中显示 CompanyName 和 CompanyLogo:Xaml:
<ListView Grid.Column="0" Grid.Row="0"
x:Name="MainListView"
HasUnevenRows="True"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
ItemTapped="MainListView_ItemTapped"
SeparatorColor="DarkGray">
<ListView.ItemTemplate>
<DataTemplate>
<ImageCell ImageSource="{Binding CompanyLogo}"
Text="{Binding CompanyName}"
TextColor="Black"
/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
【问题讨论】:
标签: xaml xamarin xamarin.forms httpclient webclient