Search code examples
c#xamluwprapidapi

I need help to get data from a Rapid API Public Holidays


I am trying to get the public holidays for my uwp application. I used this code

var client = new HttpClient();
      var request = new HttpRequestMessage
      {
          Method = HttpMethod.Get,
          RequestUri = new Uri("https://public-holiday.p.rapidapi.com/2023/SG"),
          Headers =
          {
              { "X-RapidAPI-Key", "API-Key" },
              { "X-RapidAPI-Host", "public-holiday.p.rapidapi.com" },
          },
      };
      using (var response = await client.SendAsync(request))
      {
          response.EnsureSuccessStatusCode();
          var body = await response.Content.ReadAsStringAsync();
          var serializer = new DataContractJsonSerializer(typeof(RootObj));
          Debug.WriteLine(body);
          var ms = new MemoryStream(Encoding.UTF8.GetBytes(body));
          var data = (RootObj)serializer.ReadObject(ms);
          return data;
      }

I did get the Json respond when I put debug.WriteLine(body) but when I try to use this code in the MainPage.xaml.cs,

RootObj myHolidays = await GetHolidays();
holidayTextBlock.Text = myHolidays.name + " - " + myHolidays.date + " - " + myHolidays.type;

RootObj:

        public class RootObj
        {
            [DataMember]
            public string date { get; set; }
            [DataMember]
            public string localName { get; set; }
            [DataMember]
            public string name { get; set; }
            [DataMember]
            public string countryCode { get; set; }
            [DataMember]
            public bool @fixed { get; set; }
            [DataMember]
            public bool global { get; set; }
            [DataMember]
            public object counties { get; set; }
            [DataMember]
            public object launchYear { get; set; }
            [DataMember]
            public string type { get; set; }
        }

I get null for the name, date and type even though I tested the end point it showed something as well as it showed in the debug print statement. Any help would be appreciated. Thanks.


Solution

  • Check the type of return value of that API. If it is an array of a class, specify [class name][] as the type for DataContractJsonSerializer. Don't forget to insert using before MemoryStream to ensure it would be disposed.

    var serializer = new DataContractJsonSerializer(typeof(RootObj[]));
    using var ms = new MemoryStream(Encoding.UTF8.GetBytes(body));
    var data = (RootObj[])serializer.ReadObject(ms);