How to Bind JSON Data to Xamarin.Forms ListView?
You can bind the data from JSON (JavaScript Object Notation) file in Xamarin.Forms SfListView using the ItemsSource property.
XAML
The JSON data can be bound to the SfListView ItemsSource property.
<syncfusion:SfListView x:Name="listView" ItemSize="70" ItemsSource="{Binding ItemsSource}"> <syncfusion:SfListView.ItemTemplate> <DataTemplate> <ViewCell> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Label Grid.Column="0" Text="{Binding Converter={StaticResource converter}, ConverterParameter=Value1}" HorizontalOptions="Start" TextColor="Black" FontSize="16" FontAttributes="Bold"/> <Label Grid.Column="1" Text="{Binding Converter={StaticResource converter}, ConverterParameter=Value2}" HorizontalOptions="Start" TextColor="Black" FontSize="16" FontAttributes="Bold"/> </Grid> </ViewCell> </DataTemplate> </syncfusion:SfListView.ItemTemplate> </syncfusion:SfListView>
C#
Accessed the JSON file from local folder and StreamReader reads the data to return as a dynamic object.
public ViewModel() { var assembly = typeof(MainPage).GetTypeInfo().Assembly; Stream stream = assembly.GetManifestResourceStream("ListViewXamarin.Data.Data.json"); using (StreamReader sr = new StreamReader(stream)) { var jsonText = sr.ReadToEnd(); ItemsSource = JsonConvert.DeserializeObject<dynamic>(jsonText); } }
C#
Dynamic object value converted by ExpandoObject to show the values.
public class DynamicToPathValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return value; ExpandoObject busniessObject = JsonConvert.DeserializeObject<ExpandoObject>(value.ToString()); var jsonList = busniessObject.ToList(); if (parameter.Equals("Value1")) return jsonList[0].Value; if (parameter.Equals("Value2")) return jsonList[1].Value; return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
Download the sample from GitHub.
Conclusion
I hope you enjoyed learning about how bind JSON data to Xamarin.Forms ListView.
You can refer to our Xamarin.Forms ListView feature tour page to know about its other groundbreaking feature representations. You can also explore our Xamarin.Forms ListView documentation to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!