Share via

Load List from API

Anonymous
2023-11-23T18:48:37.88+00:00

I have the below code in .NET MAUI here I load questions , this is hardcoded , I want to load it from api, please suggest

https://sheet2api.com/v1/wlS0h0USxm9p/quiz

  public List<Question> Questions { get; set; } = new List<Question>();


 
            Question q1 = new Question
            {
                QuestionTitle = "What is the capital of France?",
                Options = new List<string>() { "Rennes", "Lyon", "Paris", "Bern" },
                Answer = "Paris"
            };

            Question q2 = new Question
            {
                QuestionTitle = "What is the capital of England?",
                Options = new List<string>() { "London", "Manchester", "Glasgow", "Edinburgh" },
                Answer = "London"
            };

 Questions.AddRange(new List<Question> { q1, q2 });
 

 public class Question
    {
        public string QuestionTitle { get; set; } = string.Empty;
        public IEnumerable<string> Options { get; set; } = new List<string>();
        public string Answer { get; set; } = string.Empty;
    }


Developer technologies | .NET | .NET Multi-platform App UI
0 comments No comments

Answer accepted by question author

Anonymous
2023-11-24T04:04:28.95+00:00

Hello,

Firstly, based on your Json data, you need to create a Question class like following code.

public class Question
    {

    public int No { get; set; }

    public string QuestionTitle { get; set; }

    public string Opt1 { get; set; }

    public string Opt2 { get; set; }

    public string Opt3 { get; set; }

    public string Opt4 { get; set; }

    public string Answer { get; set; }
}

Then you can use HttpClient to request Json data from your api. After requesting was successful, we can get the Json data, we can convert Json Data to Object by Newtonsoft.Json nuget packages, you need to install it in NuGet package manage before you used it.

  async Task<List<Question>> GetApiData()
   {
       string apiUrl = "https://sheet2api.com/v1/wlS0h0USxm9p/quiz"; 
       List<Question> Questions = new List<Question>();
       using (HttpClient client = new HttpClient())
       {
           try
           {
               // Make a GET request to the API
               HttpResponseMessage response = await client.GetAsync(apiUrl);

              // Check if the request was successful (status code 200)
               if (response.IsSuccessStatusCode)
               {
                   // Read the content of the response
                   string jsonString = await response.Content.ReadAsStringAsync();


                  // Deserialize the JSON string into an object
                   Questions = JsonConvert.DeserializeObject<List<Question>>(jsonString);
                   
                   // Now you can work with the 'apiData' object
                   Console.WriteLine("Received data:");
                  
               }
               else
               {
                   Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
               }
           }
           catch (Exception ex)
           {
               Console.WriteLine($"Error: {ex.Message}");
           }
       }
      return Questions;
   }

In the end, you can get the List<Question> by invoking following code.

 List<Question> res= await GetApiData();

Best Regards,

Leon Lu


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.