We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

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

Platform: Xamarin.Forms |
Control: SfChart |
Published Date: August 26, 2019 |
Last Revised Date: August 26, 2019

JSON data cannot be bound directly to SfChart, 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.

2X faster development

The ultimate Xamarin UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile