How to Easily Load JSON Data in .NET MAUI TreeView? | Syncfusion Blogs
Detailed Blog page Skeleton loader

TL;DR: Let’s see how to load JSON data into the .NET MAUI TreeView effortlessly. This blog guides you through fetching JSON data from a URI, storing it locally, and binding it to the TreeView control. Perfect for creating intuitive navigation and hierarchical data views in .NET MAUI apps!

The Syncfusion .NET MAUI TreeView (SfTreeView) control displays data in a tree structure, letting you expand and collapse nodes. It is optimized for smooth scrolling and efficient data reuse. You can bind data, create nodes, and customize the UI easily. It also supports different selection modes, complete UI customization, and MVVM commands for better performance.

This blog teaches you how to visualize JSON data in the .NET MAUI TreeView with a hierarchical structure.

Data can be populated in the TreeView in two different modes:

  • Bound and
  • Unbound modes.

Here, we’ll bind JSON data in the .NET MAUI TreeView in bound mode using the ItemsSource property.

Let’s get started!

Populate JSON data collection from a URI

In modern mobile app development, fetching data from remote sources and storing it locally for offline use or caching purposes is essential. With .NET MAUI, you’ll often need to retrieve JSON data from a URI and store it for later access.

Here’s how to do this efficiently in a few steps. 

Step 1: Install the Newtonsoft.Json NuGet package

To easily work with JSON data in .NET MAUI, you’ll need the Newtonsoft.Json library. This popular library allows you to serialize and deserialize JSON data with ease. To do so,

  • In your .NET MAUI project, open the NuGet Package Manager.
  • Search for Newtonsoft.Json.
  • Then, install the latest stable version of the package.

This library is essential for converting your JSON string into objects and vice versa.

Step 2: Download JSON data using HttpClient and store it locally

Now that you have the necessary library installed, the next step is to fetch the JSON data from a URI, deserialize it, and store it locally on the device.

Refer to the following code example.

public async Task<bool> DownloadJsonAsync()
{
    try
    {
        // Set your REST API url here
        var url = "https://jayaleshwari.github.io/treeview-json-data/TaskDetails.json";

        // Sends request to retrieve data from the web service for the specified Uri
        var response = await httpClient.GetAsync(url);
        
        using (var stream = await response.Content.ReadAsStreamAsync()) // Reads data as stream
        {
            // Gets the path to the specified folder
            var localFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
            var newpath = Path.Combine(localFolder, "Data.json"); // Combine path with the file name

            var fileInfo = new FileInfo(newpath);
            File.WriteAllText(newpath, String.Empty); // Clear file content

            // Creates a write-only file stream
            using (var fileStream = fileInfo.OpenWrite())
            {
                // Reads data from the current stream and writes to the destination stream (fileStream)
                await stream.CopyToAsync(fileStream);
            }
        }
    }
    catch (OperationCanceledException e)
    {
        System.Diagnostics.Debug.WriteLine(@"ERROR {0}", e.Message);
        return false;
    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.WriteLine(@"ERROR {0}", e.Message);
        return false;
    }

    return true;
}

Populating tree hierarchy using .NET MAUI TreeView and JSON data

Using TreeView is an effective solution in scenarios where you need to visualize hierarchical data. When the data source is a JSON file, you can bind it to the ItemsSource property of the .NET MAUI TreeView control and display it in a tree structure. 

Step 1: Define a model class matching the JSON structure

Let’s define a model class that matches the structure of the JSON data. For example, if your JSON data represents a collection of tasks, each task may have subtasks, and so on.

Refer to the following code example. 

public class TaskDetails
{        
    public int TaskID { get; set; }
    public string TaskName { get; set; }        
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public double Duration { get; set; }
    public string Progress { get; set; }
    public string Priority { get; set; } 
    public bool IsParent { get; set; }

    public ObservableCollection<TaskDetails> SubTaskDetails { get; set; }

    internal int ParentItem { get; set; }

    public TaskDetails()
    {
        SubTaskDetails = new ObservableCollection<TaskDetails>();
    }
}

In this example, the SubTaskDetails allows each task to have children, which is essential for representing hierarchical data in a tree structure.

To properly bind data in the SfTreeView.ItemsSource with the MVVM pattern in .NET MAUI, the ViewModel must define a property that will hold the data collection. This collection will be bound to the ItemsSource of the SfTreeView.

So, in the ViewModel, we will define a property, typically as an ObservableCollection, which will update the view automatically when the data changes.

Refer to the following code example.

public class TreeViewViewModel : INotifyPropertyChanged
{
    private IList<TaskDetails> jsonCollection;

    public IList<TaskDetails> JSONCollection
    {
        get
        {
            return jsonCollection;
        }
        set
        {
            jsonCollection = value;
            OnPropertyChanged(nameof(JSONCollection));
        }
    }
}

Step 2: Load JSON data and deserialize it into the ViewModel

Next, load the JSON data and deserialize it into a collection of TaskDetails objects. To download and deserialize the JSON data, follow the pattern described earlier.

private async void GenerateSource()
{
    isDownloaded = await DataService.DownloadJsonAsync();
    
    if (isDownloaded)
    {
        var localFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        var fileText = File.ReadAllText(Path.Combine(localFolder, "Data.json"));

        // Read data from the local path and set it to the collection bound to the ListView.
        JSONCollection = JsonConvert.DeserializeObject<IList>(fileText);                
    }
}

Step 3: Configure the .NET MAUI TreeView in XAML

In your XAML file, define the .NET MAUI TreeView control and bind it to the data model. The ItemsSource property will be bound to the collection of tasks, and the hierarchical structure will be defined by the ChildPropertyName.

<syncfusion:SfTreeView x:Name="treeView" 
                       ItemTemplateContextType="Node"                          
                       ItemsSource="{Binding JSONCollection}"                           
                       ChildPropertyName="SubTaskDetails"/>

Refer to the following image.

Loading JSON Data in .NET MAUI TreeView
Loading JSON data in .NET MAUI TreeView

GitHub reference

For more details, refer to the loading JSON data in the .NET MAUI TreeView GitHub demo.

Conclusion

Thanks for reading! Following these steps, you can successfully populate the Syncfusion .NET MAUI TreeView with JSON data. This allows you to present hierarchical data structures in a user-friendly way. Combining the Newtonsoft.Json package for data handling and TreeView for visualization makes it easy to implement dynamic, tree-like interfaces in your .NET MAUI apps.

Existing customers can access the new version of Essential Studio® on the License and Downloads page. If you aren’t a Syncfusion customer, try our 30-day free trial to experience our fantastic features.

Feel free to reach out via our support forumsupport portal, or feedback portal. We’re here to help!

Related blogs

Be the first to get updates

Jayaleshwari N

Meet the Author

Jayaleshwari N

Jayaleshwari N works for Syncfusion as a product manager. She has been a .NET developer since 2013, and has experience in the development of custom controls in Xamarin and MAUI platforms.