Marc-Anthony
Marc-Anthony

Reputation: 102

Unable to parse JSON array API in Xamarin.Forms to ListView

I am trying to parse a JSON Array with no success.I researched all possible solutions but none seems to work for my solution.

This is the JSON returning from server:

{"events":[{"url":"xxxxx","title":"xxxxx","date":"xxxx","time":"xxxx"},{"url":"xxxxx","title":"xxxxx","date":"xxxx","time":"xxxx"}]}

This is my RootObject class :

public class ChristmasEvent
{
    [JsonProperty("events")]
    public List<Event> Events { get; set; }
}

public class Event
{
    [JsonProperty("url")]
    public string Url { get; set; }

    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("date")]
    public string Date { get; set; }

    [JsonProperty("time")]
    public string Time { get; set; }
}

Web Service class

 private const string Url = "http://xxxx/events";
 private HttpClient _httpClient = new HttpClient();

 var apiResource = await _httpClient.GetStringAsync(Url);

 var tr = JsonConvert.DeserializeObject<List<ChristmasEvent>>(apiResource);

 ObservableCollection<ChristmasEvent> christmasEvents = new ObservableCollection<ChristmasEvent>(tr);

 EventListView.ItemsSource = christmasEvents;

XAML File

<ListView x:Name="EventListView">
      <ListView.ItemTemplate>
        <DataTemplate>
           <ViewCell>
              <StackLayout>
                 <Label Text="{Binding title}" />
                 <Label Text="{Binding date, StringFormat='{0:MMMM dd, yyyy}'}"/>
              </StackLayout>
          </ViewCell>
         </DataTemplate>
       </ListView.ItemTemplate>
     </ListView>

I am unsure why this is not working and seeking to find what i am doing wrong..

Upvotes: 1

Views: 855

Answers (1)

Artem
Artem

Reputation: 2075

1) You are trying to deserialize to a List of items, while you should deserialize as the item itself (as I can see from the JSON you provided):

var tr = JsonConvert.DeserializeObject<ChristmasEvent>(apiResource);

Then

var events = new ObservableCollection<Event>(tr.Events);
EventListView.ItemsSource = events;

2) You bind to lowercase properties. Bind to Title instead of title and Date instead of date. Or simply name your C# properties as lowercase. For example:

<Label Text="{Binding Title}" />

3) Your Date property is declared as a string. But in your view you are trying to format it (with StringFormat) as a date. Make it a DateTime property. You may also want to change your Time property type to TimeSpan.

public DateTime Date { get; set; }

Upvotes: 1

Related Questions