Show data coming from a JSON in a listview

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 in a listview after deserializing, the data does not show what I want.

When I the app, all data is received.

    
asked by anonymous 20.12.2017 / 18:55

1 answer

0

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

You have two viable alternatives here:

1. Pass a list of strings to 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. Write 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}";
    } 
}
    
20.12.2017 / 19:42