c# - Xamarin.Forms JSON 对象到 Listview

标签 c# json xamarin xamarin.forms

我正在尝试解析此 JSON 对象并将其绑定(bind)到我在 Xamarin.Forms 中的 ListView。

我完全不知道如何处理它,因为我是 Xamarin Forms 的新手。

有更简单的方法吗?

我返回的 JSON 对象

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret"
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette"
  }
]

这是我处理 REST json 响应的代码

public class RestClient
    {
        public RestClient ()
        {
        }

        public async Task<User[]> GetUsersAsync () {

            var client = new System.Net.Http.HttpClient ();

            client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com");

            var response = client.GetAsync("users");

            var usersJson = response.Result.Content.ReadAsStringAsync().Result;

            var rootobject = JsonConvert.DeserializeObject<Rootobject>(usersJson);

            return rootobject.Users;

        }
    }

用户.cs

    public class Rootobject
        {
            public User[] Users { get; set; }
        }

        public class User
        {
            public string id { get; set; }
            public string username { get; set; }
        }

ListView Form Code
var sv = new RestClient ();
            var es = sv.GetUsersAsync();
            Xamarin.Forms.Device.BeginInvokeOnMainThread (() => {
                Debug.WriteLine("Found " + es.Result.Length + " users");
                listView.ItemsSource = es.Result;
            });

XAML

public ListViewPage ()
        {
            Title = "Users";

            var sv = new RestClient ();
            var es = sv.GetUsersAsync();
            Xamarin.Forms.Device.BeginInvokeOnMainThread (() => {
                Debug.WriteLine("Found " + es.Result.Length + " users");
                listView.ItemsSource = es.Result;
            });


            listView = new ListView ();
            listView.ItemTemplate = new DataTemplate(typeof(TextCell));
            listView.ItemTemplate.SetBinding(TextCell.TextProperty, "username");

            listView.ItemTemplate = new DataTemplate(typeof(ItemCell));

            Content = new StackLayout { 
                Children = {
                    listView
                }
            };
        }

最佳答案

您的异步调用不正确。如果您必须在构造函数中执行此操作(这不是执行此操作的最佳位置),您将希望使用 ContinueWith 作为 using Task.Result 不应使用。此外,由于结果是一个阻塞调用,您在构造 ListView 之前分配了项目源,并且您得到了一个空引用异常。

试试这个:

public class ListViewPage : ContentPage
{
    private readonly ListView listView;

    public ListViewPage()
    {
        Title = "Users";

        this.listView = new ListView {ItemTemplate = new DataTemplate(typeof (TextCell))};
        this.listView.ItemTemplate.SetBinding(TextCell.TextProperty, "username");

        Content = new StackLayout
        {
            Children = { this.listView }
        };

        var sv = new RestClient();
        var es = sv.GetUsersAsync().ContinueWith(t =>
        {
            if (t.Status == TaskStatus.RanToCompletion)
            {
                Debug.WriteLine("Found {0} users.", t.Result.Length);
                Device.BeginInvokeOnMainThread(() => this.listView.ItemsSource = t.Result);
            }
        });
    }
}

一个稍微好一点的选择(但也不完美)是覆盖出现的方法并且标记是异步的。这样您就可以在异步 REST 调用方法上使用 await 。请注意,除非添加额外的代码,否则每次出现 View 时都会调用它。

    protected override async void OnAppearing()
    {
        base.OnAppearing();

        try
        {
            var sv = new RestClient();
            // activate/show spinner here
            this.listView.ItemsSource = await sv.GetUsersAsync();
            // inactivate/hide spinner here
        }
        catch (Exception exception)
        {
            this.DisplayAlert("Error", exception.Message, "OK");
        }
    }

关于c# - Xamarin.Forms JSON 对象到 Listview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28829904/

相关文章:

.net - 如果附加了调试器,为什么我的堆栈跟踪仅包含行号?

c# - 牛顿软件 JSON : Error getting value from 'NativeCalendarName' on 'System.Globalization.DateTimeFormatInfo'

json - 使用 Bool 类型从 JSON 定义未知值

json - 在 Go 中解码通过 MQTT 发布的 JSON 对象

c# - 使用 Sustainsys 和 Azure 的 SAML 单点注销,给出消息无效错误

c# - 从azure存储异步下载blob并将其保存在DataTable中

json - 将 JSON 对象插入数据库

android - Android Q 中的 Landroid/view/LayoutInflater 类中没有字段 mConstructorArgs

c# - 传递给套接字监听器的参数无效

c# - 编码 mp3 或其他音乐文件