Show data from a JSON in a listview

Asked

Viewed 124 times

1

namespace Monitorizacao.UI.Pages
{

    public class Post {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
    }

    public partial class TestAPIPage : ContentPage
    {
        private const string url = "https://jsonplaceholder.typicode.com/posts";
        private HttpClient _client = new HttpClient();
        private ObservableCollection<Post> _posts;

        public TestAPIPage()
        {
            InitializeComponent();

        }

        protected override async void OnAppearing()
        {
            var content = await _client.GetStringAsync(url);
            var posts = JsonConvert.DeserializeObject<List<Post>>(content);

            _posts = new ObservableCollection<Post>(posts);
            List.ItemsSource = _posts;
            Console.Write(posts);
            base.OnAppearing();
        }


    }
}

I have a JSON and when I try to show it on a listview after deserialize, the data does not show what I want.

When I do debug from the app, all data is received.

  • Henry, run a test and change the line List.ItemsSource = _posts; for List.ItemsSource = _posts.Select(p => p.Title).ToList();

1 answer

0


What happens is that the listview will call the method ToString of each object to show it.

You have two viable alternatives here:

1. Pass a list of strings to the listview

protected override async void OnAppearing()
{
    var content = await _client.GetStringAsync(url);
    var posts = JsonConvert.DeserializeObject<List<Post>>(content);

    _posts = new ObservableCollection<Post>(posts);
    List.ItemsSource = _posts.Select(x => x.Title).ToList();
    // (^) onde tem x.Title, você muda para a propriedade que queres mostrar        

    Console.Write(posts);
    base.OnAppearing();
}

2. Writing a method ToString in Post to show what you want in listview

public class Post 
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }

    public string ToString()
    {
        return $"{Id} - Título: {Title}";
    } 
}
  • Man, thank you so much, I’ve been trying to fix this for, like, five hours

  • guy you have skype?

  • @Henriquerodrigues I have, why? (As soon as the delay, I was on vacation)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.