Articles in this section
Category / Section

How to pass a JSON array to Xamarin.Forms Chart?

1 min read

JSON data cannot be bound directly to Xamarin Charts, so we should deserialize the JSON data to a bindable format. You can use the open source NuGet Newtonsoft.Json to serialize and deserialize the JSON objects.

 

The following steps explain how to pass JSON data to SfChart.

 

JSON data

{
 'Country': 'USA',
 'Count': 46
}, {
 'Country': 'China',
 'Count': 36
}, {
 'Country': 'Japan',
 'Count': 63
}, {
 'Country': 'Australia',
 'Count': 54
}, {
 'Country': 'France',
 'Count': 50
}

 

Step 1: Create a data model to store JSON data.

public class GoldMedal
{
   public string Country { get; set; }
   public int Count { get; set; }
}

 

Step 2: Create a ViewModel to store a collection of model objects.

public class ViewModel
{
   public ObservableCollection<GoldMedal> Medal { get; set; }
}

 

Step 3: Deserialize the JSON data as a collection of data models.

public ChartPage()
{
   InitializeComponent();
   string jsonData = @"{'Medal':[{'Country':'USA','Count':46},{'Country':'China','Count':36},{'Country':'Japan','Count':63},{'Country':'Australia','Count':54},{'Country':'France','Count':50}]}";
 
   var jsonDataCollection = JsonConvert.DeserializeObject<ViewModel>(jsonData);
   BindingContext = jsonDataCollection;
}

 

Step 4: Bind the deserialized JSON data to the ChartSeries using the XBindingPath and YBindingPath properties.

<chart:SfChart x:Name="chart">
    . . .
 
     <chart:SfChart.Series>
     <chart:ColumnSeries x:Name="series"  ItemsSource="{Binding Medal}" XBindingPath="Country" YBindingPath="Count"/> 
     </chart:SfChart.Series>
 
</chart:SfChart>

You can download the complete sample.

Output

Bind the JSON data to Xamarin.Forms Chart.


Conclusion

I hope you enjoyed learning how to pass a JSON array to Xamarin.Forms Chart.

You can refer to our Xamarin. Forms Chart feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Xamarin. Forms Charts example 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 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 (0)
Please  to leave a comment
Access denied
Access denied