【发布时间】:2019-01-17 19:00:04
【问题描述】:
我可以解决这个错误。我想显示大量 API 数据的ListView。
例如 API 包含此类数据:
[{"id":"666","employee_name":"xyz","employee_salary":"123","employee_age":"23","profile_image":""}]
错误截图:
我将 JSON 转换为 c# 后制作的 Class.cs
public class employees
{
public string id { get; set; }
public string employee_name { get; set; }
public string employee_salary { get; set; }
public string employee_age { get; set; }
public string profile_image { get; set; }
}
这是 LoadData() 用于调用 API 的 XAML.cs 文件
public async void LoadData()
{
var content = "";
HttpClient client = new HttpClient();
var RestURL = "MY API";
client.BaseAddress = new Uri(RestURL);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(RestURL);
content = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<List<employees>>(content);
ListView1.ItemsSource = Items;
}
这是 Xamarin.Forms 的 XAML 文件:
<StackLayout BackgroundColor="White">
<ListView x:Name="ListView1" RowHeight="60">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical" Padding="8,0,8,0">
<Label Text="{Binding id}" TextColor="#000" FontSize="14" LineBreakMode="TailTruncation" />
<Label Text="{Binding employee_name}" TextColor="#000" LineBreakMode="TailTruncation" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
【问题讨论】:
-
你的问题是什么?到目前为止,您尝试过什么?
-
现有数百个教程和示例应用程序将向您展示如何从远程 API 加载数据并显示它。
-
你有没有想过创建一个对象,并将这些json解析回一个列表,然后只设置为listview项源。
-
@Bruno Caceiro 请仔细阅读我上面列出的代码。
-
@Lee 你有任何关于你在说什么的代码示例,因为我是初学者,我不知道如何解析
标签: json api listview xamarin.forms cross-platform