How to bind JSON data in .NET MAUI TreeView (SfTreeView)?
The Syncfusion® .NET MAUI TreeView enables you to bind data from a JSON file using the ItemsSource property. This demonstration will guide you through the process of binding JSON data to the TreeView.
STEP 1: Define your data model to map the structure of your JSON data.
public class Cities
{
public string Name { get; set; }
}
public class States
{
public List<Cities> Cities { get; set; }
public string Name { get; set; }
}
public class Countries
{
public List<States> States { get; set; }
public string Name { get; set; }
}
STEP 2: Access the JSON file from the local folder and use StreamReader to read the data and return as an ObservableCollection property.
private void GenerateSource()
{
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("MAUITreeView.Data.navigation.json");
using (StreamReader sr = new StreamReader(stream))
{
var jsonText = sr.ReadToEnd();
ImageNodeInfo = new ObservableCollection<Countries>();
var MyArrayData = JsonConvert.DeserializeObject<List<Countries>>(jsonText);
foreach (var data in MyArrayData)
{
ImageNodeInfo.Add(data);
}
}
}
STEP 3: Bind the JSON collection data to the ItemSource.
<syncfusion:SfTreeView x:Name="treeView"
ItemHeight="25"
Indentation="20"
ExpanderWidth="25"
ItemsSource="{Binding ImageNodeInfo}"
AutoExpandMode="RootNodesExpanded"
NodePopulationMode="Instant">
<syncfusion:SfTreeView.HierarchyPropertyDescriptors>
<treeviewengine:HierarchyPropertyDescriptor TargetType="{x:Type local:Countries}" ChildPropertyName="States"/>
<treeviewengine:HierarchyPropertyDescriptor TargetType="{x:Type local:States}" ChildPropertyName="Cities"/>
</syncfusion:SfTreeView.HierarchyPropertyDescriptors>
<syncfusion:SfTreeView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid x:Name="grid" BackgroundColor="Transparent">
<Label LineBreakMode="WordWrap"
FontSize="14"
Text="{Binding Name}"
TextColor="Black"
VerticalTextAlignment="Center"/>
</Grid>
</ViewCell>
</DataTemplate>
</syncfusion:SfTreeView.ItemTemplate>
</syncfusion:SfTreeView>
Output
Download the complete sample from GitHub
Conclusion
I hope you enjoyed learning how to bind JSON data in .NET MAUI TreeView.
You can refer to our .NET MAUI TreeView feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started with configuration specifications.
You can also explore our .NET MAUI TreeView example to understand how to create and manipulate data.
You can check out our components from the License and Downloads page for current customers. If you are new to Syncfusion®, try our 30-day free trial to check out our other controls.
Please let us know in the comments section if you have any queries or require clarification. Contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!