使用RestApi在Xamarin中实现ListView

3

我无法解决这个错误。我想显示大量API数据的ListView

例如,API包含以下类型的数据:

[{"id":"666","employee_name":"xyz","employee_salary":"123","employee_age":"23","profile_image":""}]

错误截图: 错误截图

Class.cs是我在将JSON转换为c#后创建的

 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; }

    }

这是XAML.cs文件,LoadData()用于调用API

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加载数据并显示它。 - Jason
你有没有考虑创建一个对象,将这些JSON解析为列表,然后仅将其设置为ListView项目源? - Lee
@Bruno Caceiro,请仔细查看我上面列出的代码。 - Hashir Malik
你的错误是什么?你没有发布错误。 - Bruno Caceiro
@BrunoCaceiro 我在上面附了一张图片。请查看它。 - Hashir Malik
显示剩余4条评论
2个回答

0

首先需要创建一个本地模型类:

public class TodoItem
{
    public string id { get; set; }

    public string employee_name { get; set; }

    public string employee_salary{ get; set; }

    public bool employee_age { get; set; }

    public bool profile_image { get; set; }
}

RestService 中可以使用 TodoItem:
public List<TodoItem> Items { get; private set; }

public async Task<List<TodoItem>> RefreshDataAsync ()
{
   Items = new List<TodoItem> ();
 // RestUrl = http://developer.xamarin.com:8081/api/todoitems
   var uri = new Uri (string.Format (Constants.RestUrl, string.Empty));
   try {
       var response = await client.GetAsync (uri);
       if (response.IsSuccessStatusCode) {
           var content = await response.Content.ReadAsStringAsync ();
           Items = JsonConvert.DeserializeObject <List<TodoItem>> (content);
        }
    } catch (Exception ex) {
           Debug.WriteLine (@"ERROR {0}", ex.Message);
    }
    return Items;
}

最后,您可以将listview的itemsource设置如下:

listView.ItemsSource = await RestService.RefreshDataAsync();

注意:这里有一个官方示例供您参考。

我无法解决这个错误,我想显示大量的API数据列表

在列表视图中显示大量数据,这里有一种分页显示方法。获取API数据后,将它们保存在本地的CacheListData中。不要直接将其设置为listView.ItemsSource。您需要创建一个ItemListData来从CacheListData中添加数据。添加的数据数量根据您想要显示的次数而定。当列表视图滚动到底部时,显示添加更多滑动方法以重新加载下一页数据。

通常,解决方案是先将大量数据缓存到本地。然后按页面逐渐获取数据进行显示。这里有一个解决方案链接可供参考。


江,请帮我检查一下我上面列出的代码,告诉我哪里出错了以及我应该怎么做。谢谢。 - Hashir Malik
从图像显示中出现的错误 <<无法将当前 JSON 对象反序列化为类型 'System.Collections.Generic.List。>> 您需要检查来自 API 的 Json 数据。这里是一个解决方案供您参考。(https://stackoverflow.com/questions/49772027/cannot-deserialize-the-current-json-object-xamarin-forms) - Junior Jiang

0

您正在使用错误的端点,您应该使用此端点来检索员工列表

 var RestURL = "http://dummy.restapiexample.com/api/v1/employees/";  

你可以查看API文档

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接