Tuesday, January 21, 2025
HomeC#Tips on how to Simply Load JSON Information in .NET MAUI TreeView?

Tips on how to Simply Load JSON Information in .NET MAUI TreeView?


TL;DR: Let’s see the best way to load JSON knowledge into the .NET MAUI TreeView effortlessly. This weblog guides you thru fetching JSON knowledge from a URI, storing it regionally, and binding it to the TreeView management. Excellent for creating intuitive navigation and hierarchical knowledge views in .NET MAUI apps!

The Syncfusion .NET MAUI TreeView (SfTreeView) management shows knowledge in a tree construction, letting you broaden and collapse nodes. It’s optimized for clean scrolling and environment friendly knowledge reuse. You may bind knowledge, create nodes, and customise the UI simply. It additionally helps completely different choice modes, full UI customization, and MVVM instructions for higher efficiency.

This weblog teaches you the best way to visualize JSON knowledge within the .NET MAUI TreeView with a hierarchical construction.

Information will be populated within the TreeView in two completely different modes:

Right here, we’ll bind JSON knowledge within the .NET MAUI TreeView in certain mode utilizing the ItemsSource property.

Let’s get began!

Populate JSON knowledge assortment from a URI

In trendy cell app growth, fetching knowledge from distant sources and storing it regionally for offline use or caching functions is important. With .NET MAUI, you’ll usually have to retrieve JSON knowledge from a URI and retailer it for later entry.

Right here’s how to do that effectively in a couple of steps. 

Step 1: Set up the Newtonsoft.Json NuGet package deal

To simply work with JSON knowledge in .NET MAUI, you’ll want the Newtonsoft.Json library. This in style library means that you can serialize and deserialize JSON knowledge with ease. To take action,

  • In your .NET MAUI venture, open the NuGet Bundle Supervisor.
  • Seek for Newtonsoft.Json.
  • Then, set up the newest steady model of the package deal.

This library is important for changing your JSON string into objects and vice versa.

Step 2: Obtain JSON knowledge utilizing HttpClient and retailer it regionally

Now that you’ve got the mandatory library put in, the subsequent step is to fetch the JSON knowledge from a URI, deserialize it, and retailer it regionally on the system.

Discuss with the next code instance.

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

        // Sends request to retrieve knowledge from the net service for the desired Uri
        var response = await httpClient.GetAsync(url);
        
        utilizing (var stream = await response.Content material.ReadAsStreamAsync()) // Reads knowledge as stream
        {
            // Will get the trail to the desired folder
            var localFolder = System.Atmosphere.GetFolderPath(System.Atmosphere.SpecialFolder.LocalApplicationData);
            var newpath = Path.Mix(localFolder, "Information.json"); // Mix path with the file identify

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

            // Creates a write-only file stream
            utilizing (var fileStream = fileInfo.OpenWrite())
            {
                // Reads knowledge from the present stream and writes to the vacation spot 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 utilizing .NET MAUI TreeView and JSON knowledge

Utilizing TreeView is an efficient answer in eventualities the place it is advisable to visualize hierarchical knowledge. When the information supply is a JSON file, you may bind it to the ItemsSource property of the .NET MAUI TreeView management and show it in a tree construction. 

Step 1: Outline a mannequin class matching the JSON construction

Let’s outline a mannequin class that matches the construction of the JSON knowledge. For instance, in case your JSON knowledge represents a group of duties, every job might have subtasks, and so forth.

Discuss with the next code instance. 

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 Length { get; set; }
    public string Progress { get; set; }
    public string Precedence { get; set; } 
    public bool IsParent { get; set; }

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

    inner int ParentItem { get; set; }

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

On this instance, the SubTaskDetails permits every job to have youngsters, which is important for representing hierarchical knowledge in a tree construction.

To correctly bind knowledge within the SfTreeView.ItemsSource with the MVVM sample in .NET MAUI, the ViewModel should outline a property that can maintain the information assortment. This assortment might be certain to the ItemsSource of the SfTreeView.

So, within the ViewModel, we’ll outline a property, usually as an ObservableCollection, which is able to replace the view routinely when the information modifications.

Discuss with the next code instance.

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

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

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

Subsequent, load the JSON knowledge and deserialize it into a group of TaskDetails objects. To obtain and deserialize the JSON knowledge, observe the sample described earlier.

personal async void GenerateSource()
{
    isDownloaded = await DataService.DownloadJsonAsync();
    
    if (isDownloaded)
    {
        var localFolder = Atmosphere.GetFolderPath(Atmosphere.SpecialFolder.LocalApplicationData);
        var fileText = File.ReadAllText(Path.Mix(localFolder, "Information.json"));

        // Learn knowledge from the native path and set it to the gathering certain to the ListView.
        JSONCollection = JsonConvert.DeserializeObject<IList>(fileText);                
    }
}

Step 3: Configure the .NET MAUI TreeView in XAML

In your XAML file, outline the .NET MAUI TreeView management and bind it to the information mannequin. The ItemsSource property might be certain to the gathering of duties, and the hierarchical construction might be outlined by the ChildPropertyName.

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

Discuss with the next picture.

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

GitHub reference

For extra particulars, consult with the loading JSON knowledge within the .NET MAUI TreeView GitHub demo.

Conclusion

Thanks for studying! Following these steps, you may efficiently populate the Syncfusion .NET MAUI TreeView with JSON knowledge. This lets you current hierarchical knowledge constructions in a user-friendly means. Combining the Newtonsoft.Json package deal for knowledge dealing with and TreeView for visualization makes it simple to implement dynamic, tree-like interfaces in your .NET MAUI apps.

Current prospects can entry the brand new model of Important Studio® on the License and Downloads web page. For those who aren’t a Syncfusion buyer, attempt our 30-day free trial to expertise our incredible options.

Be happy to succeed in out through our help discussion boardhelp portal, or suggestions portal. We’re right here to assist!

Associated blogs

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments