Articles in this section
Category / Section

How to load SfDataGrid dynamically with JSON data in Xamarin.Forms?

2 mins read

 

JSON data cannot be bound directly to Xamarin DataGrid. To bind SfDataGrid with JSON data, we must deserialize the JSON data to a bindable format. You can use the open source NuGet Newtonsoft.Json to serialize and deserialize JSON objects.

Xamarin.Forms have limitations in loading dynamic object (Expando object). Hence dynamic objects can be loaded only using dictionary collection. Refer the dynamic limitations for more details.

JSON data can be parsed into a dictionary collection using JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json_object).

You can then convert the list of dictionary objects to an observable collection if your data source need to respond to collection changes.

The List of Dictionary objects or the converted ObservableCollection can now be binded as ItemsSource of SfDataGrid.

Refer the below example in which the list of dictionary objects are converted as an ObservableCollection and bound to SfDataGrid.

ViewModel.cs

public class ViewModel
{
        public const string JsonData = "[{\"OrderID\":1,\"EmployeeID\":100,\"FirstName\":'Gina',\"LastName\":'Gable'}," +
                                       "{\"OrderID\":2,\"EmployeeID\":200,\"FirstName\":'Danielle',\"LastName\":'Rooney'}," +
                                      "{\"OrderID\":3,\"EmployeeID\":300,\"FirstName\":'Frank',\"LastName\":'Gable'},]" ;
                                      
       public ObservableCollection<DynamicModel> DynamicCollection { get; set; }
       public List<Dictionary<string, object>> DynamicJsonCollection { get; set; }
 
        public ViewModel()
        {
            DynamicJsonCollection = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonData);
            DynamicCollection = PopulateData();
        }
 
        private ObservableCollection<DynamicModel> PopulateData()
        {
            var data = new ObservableCollection<DynamicModel>();
            foreach (var item in DynamicJsonCollection)
            {
                var obj = new DynamicModel() { Values = item };
                data.Add(obj);
            }
            return data;
        }
}

 

DynamicModel.cs

public class DynamicModel : INotifyPropertyChanged
{
        public Dictionary<string, object> data;
 
        public event PropertyChangedEventHandler PropertyChanged;
 
        public Dictionary<string, object> Values
        {
            get
            {
                return data;
            }
            set
            {
                data = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Values"));
            }
 
        }
        public DynamicModel()
        {
            this. data = new Dictionary<string, object>();
 
        }
}

 

MainPage.cs

You can set the deserialized data to the SfDataGrid by using the below

public partial class MainPage : ContentPage
{
        private SfDataGrid grid;
        private ViewModel viewModel;
        public MainPage()
        {
            InitializeComponent();
            grid = new SfDataGrid();
            viewModel = new ViewModel();
            grid.AllowSorting = true;
            grid.AutoGenerateColumns = false;
            grid.ColumnSizer = ColumnSizer.Star;
            grid.ItemsSource = viewModel.DynamicCollection;
            grid.Columns.Add(new GridTextColumn()
            {
                HeaderText = "Order ID",
                MappingName = "Values[OrderID]",
                LineBreakMode = LineBreakMode.WordWrap,
                TextAlignment = TextAlignment.Center,
                HeaderTextAlignment = TextAlignment.Center,
            });
 
            grid.Columns.Add(new GridTextColumn()
            {
                HeaderText = "Customer ID",
                MappingName = "Values[EmployeeID]",
                LineBreakMode = LineBreakMode.WordWrap,
                TextAlignment = TextAlignment.Center,
                HeaderTextAlignment = TextAlignment.Center,
            });
 
        this.Content = grid;
 
        }
}

 

Note:

In order to apply sorting for JSON data, you have to customize the GridQueryableCollectionViewWrapper class and initialize the customized GridQueryableCollectionViewWrapper while setting the ItemSource to SfDataGrid.

 

Refer the below code example to customize the GridQueryableCollectionViewWrapper class.

public class QueryableViewExt : GridQueryableCollectionViewWrapper
{
        public QueryableViewExt(IEnumerable source, SfDataGrid grid) : base(source, grid)
        {
 
        }
 
        public override Expression<Func<string, object, object>> GetExpressionFunc(string propertyName, DataOperation operation = DataOperation.Default, DataReflectionMode reflectionMode = DataReflectionMode.Default)
        {
            Expression<Func<string, object, object>> exp = base.GetExpressionFunc(propertyName, operation, reflectionMode);
            if (exp == null)
            {
                Func<string, object, object> func;
                func = (propertyname, record) =>
                {
                    var provider = this.GetPropertyAccessProvider();
                    return provider.GetValue(record, propertyName);
                };
                exp = (propertyname, record) => func(propertyName, record);
            }
            return exp;
        }
    }

 

MainPage.cs:

// grid.ItemsSource = viewModel.DynamicCollection;
grid.ItemsSource = new QueryableViewExt(viewModel.DynamicCollection, grid);

 

Sample Link: How to load SfDataGrid dynamically with JSON data without POCO classes?

 

Conclusion

I hope you enjoyed learning about how to load SfDataGrid dynamically with JSON data in Xamarin.Forms

You can refer to our Xamarin.Forms DataGrid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications.

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 forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (5)
Please  to leave a comment
MR
Martin Richter

I just tried to rebuild the sample with the latest VS-2017 version and the latest Syncfusion 15.4.0.20 but I get an Null pointer exception in code I have no access to

Here an extract of the stacktrace.

  0xFFFFFFFFFFFFFFFF in System.Diagnostics.Debugger.Mono_UnhandledException_internal C# Annotated Frame
  0x1 in System.Diagnostics.Debugger.Mono_UnhandledException C# Annotated Frame
  0x3E in object.4b5b9e32-61ea-4e96-aced-47f0a4743d4e C# Annotated Frame
  0x94 in Syncfusion.SfDataGrid.XForms.SfDataGrid.CreateCollectionViewAdv C# Annotated Frame
  0xA in Syncfusion.SfDataGrid.XForms.SfDataGrid.CreateCollectionView C# Annotated Frame
  0x2 in Syncfusion.SfDataGrid.XForms.SfDataGrid.SetSourceList C# Annotated Frame


MR
Martin Richter

I also moved the files into a new project. Same problem.

MR
Martin Richter

Removing the QueryableViewExt, got the sample to run. But I would be happy to get a full running version.


                                            
PD
Pranay Deep

Sorting is not working


RV
Érik Vinícius

Can't I edit DataGrid data when loading it dynamically? I've tried but everytime I change a field content it becomes the same it was before.

WR
Walter Robert Ditzler

Hi,

same here - example works basically except the sorting part. implemented as well QueryableViewExt but it seems Expression<Func<string, ... is not going to be fired.

Any update on this

cheers Walter.

AH
Amir H

It works well using GridTextColumn but how can I use GridTemplateColumn and set a label text binding?

Access denied
Access denied