.netmauimobile-application.net-8.0

API Response returning null error .NET MAUI


I am trying to fetch an API from Unsplash for displaying images

however I am not able to display them because of the Error CS1579 stating : Getting error foreach statement cannot operate on variables of type Root because Root does not contain a public definition for 'GetEnumerator'

using Newtonsoft.Json;

namespace ImageAPI
{
    public partial class MainPage : ContentPage
    {
        int count = 0;
        private List<String> lst;
        private object usrName;

        public MainPage()
        {
            InitializeComponent();
            lst = new List<String>();
            BindingContext = this;
        }

        private async void OnCounterClicked(object sender, EventArgs e)
        {
            HttpClient client = new HttpClient();
            var url = "https://api.unsplash.com/search/photos/?page=1&query=office&client_id=R62b2dZL9UoHcYhxook8WAkwklTUcBHqhJEmxe5AEqY";
            try
            {
                HttpResponseMessage response = await client.GetAsync(url);
                var content = await response.Content.ReadAsStringAsync();
                var apiResponse = JsonConvert.DeserializeObject<Root>(content);

                if (response.IsSuccessStatusCode)
                {
                    if (apiResponse != null) {
                        foreach (var photo in apiResponse)
                        {
                            var username = photo.User?.Username;
                           
                             lst.Add(username);
                        }
                        imageListView.ItemsSource = lst;
                    }
                }
                else
                {
                    await DisplayAlert("Error", "Invalid response", "Ok");
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Exception", $"{ex.Message}", "Ok");
            }
        }
    }
}

The listview is therefore not getting updated and nothing is being displayed!

Help appreciated!


Solution

  • ok, I think I know where your issue is.

    I did:

    1 copy the URL in your HTTP request and copy the json in test project as TestData.json and update the property of the file to "Copy if newer" so I can read it in my test

    2 Copied the json again in visual studio, created a cs code file and used Edit-> "Past Special" -> "Past Json As Class". I then get the classes in the json generated for me by visual studio. It doesn't make it pretty and I have all in lower case however I can't see the classes you use.

    If I create the classes using the json in the link you provided then my "root" class tart with:

    public class Rootobject
    {
        public int total { get; set; }
        public int total_pages { get; set; }
        public Result[] results { get; set; }
    }
    

    This might not be what you have, note that I need to loop over result and not Rootobject, but if I do that, I can do this:

    internal class Program
    {
        static void Main(string[] args)
        {
            var content = File.ReadAllText("TestData.json");
            var apiResponse = JsonConvert.DeserializeObject<Rootobject>(content);
            if (apiResponse is null)
            {
                throw new Exception("Null json");
            }
            var lst= new List<string>();
            foreach (var photo in apiResponse.results)
            {
                var username = photo.user.username;
    
                lst.Add(username);
            }
    
            Console.WriteLine(lst.Count);
        }
    }
    

    I think you might be looping and deserializing on the wrong class and your issue isn't Maui related.