Visualize JSON Data Quickly Using WPF Charts
Tags: wpf, charts, desktop, json
Published: 2023-04-14 12:15:28

---
title: Visualize JSON Data Quickly Using WPF Charts
published: true
date: 2023-04-14 09:00:00 UTC
tags: wpf, charts, desktop, json
canonical_url: https://www.syncfusion.com/blogs/post/visualize-json-data-wpf-charts.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8w228d2hml4d5u8nlzzz.png
---
In this article, I’ll go over extracting data from JSON files and visualizing it with bar charts, line charts, and pie charts from the Syncfusion [WPF Charts](https://www.syncfusion.com/wpf-controls/charts "Syncfusion WPF Charts") control. This can be achieved with the following easy steps:

1. [Process JSON data.](#json)
2. [Deserialize the JSON data to a dynamic object.](#object)
3. [Convert the list of dynamic objects to a data table.](#table)
4. [Create beautiful charts from the data table.](#beautiful)

We will also cover how to export the charts to popular formats like PNG and JPEG. 

The final output of the demo app will look like the following.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/04/Fetch-and-Display-Advanced-JSON-Data-in-WPF-Charts-1.gif" alt="Fetch and Display Advanced JSON Data in WPF Charts" style="width:100%">

  <figcaption>Fetch and Display Advanced JSON Data in WPF Charts</figcaption>

</figure>

## <a name="json">Process JSON data</a>

[JSON](https://en.wikipedia.org/wiki/JSON "Wikipedia Link: JSON") is one of the most widely used data formats, but working with it can be challenging. In this section, we are going to see two ways data can be retrieved from a JSON string.

Follow these steps to populate a data collection from a JSON string:

**Step 1** : Install the [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/ "Newtonsoft.Json NuGet Package") NuGet package in your WPF project.

**Step 2** : Paste your JSON string into the text box or use a web service that provides order data to obtain the data, like the following example link.

[https://ej2services.syncfusion.com/production/web-services/api/Orders](https://ej2services.syncfusion.com/production/web-services/api/Orders "EJ2 Services API")

**Step 3** : In the **ViewModel** class, create required properties and methods for binding the data to the chart.

```csharp
public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
    }

    ObservableCollection<ExpandoObject> items = new ObservableCollection<ExpandoObject>();

    private string xBindingPath;
    public string XBindingPath
    {
       get
       {
           return xBindingPath;
       }
       set
       {
            xBindingPath = value;
            OnPropertyRaised(nameof(XBindingPath));

       }
   }

   private string yBindingPath;
   public string YBindingPath
   {
      get
      {
         return yBindingPath;
      }
      set
      {
         yBindingPath = value;
         OnPropertyRaised(nameof(YBindingPath));

      }
   }

   private DataTable data;
   public DataTable Data
   {
      get
      {
         return data;
      }
      set
      {
         data = value;
         OnPropertyRaised(nameof(Data));
      }
   }

   private List<string> xcolumns;

   public List<string> XColumns
   {
      get
      {
         return xcolumns;
      }
      set
      {
         xcolumns = value;
         OnPropertyRaised(nameof(XColumns));
      }
   }

   private List<string> ycolumns;

   public List<string> YColumns
   {
      get
      {
         return ycolumns;
      }
      set
      {
         ycolumns = value;
         OnPropertyRaised(nameof(YColumns));
      }
   }
}
```

**Step 4** : Retrieve the data from the JSON string and put it in the string property of the **ViewModel**.

```csharp
private string jsonData;
public string JsonData
{
    get
    {
       return jsonData;
    }
    set
    {
       if(value != jsonData)
       {
          jsonData = value;
          GetDataAsync(jsonData);
          OnPropertyRaised(nameof(JsonData));
       }
    }
}
```

## <a name="object">Deserialize the JSON data to dynamic object</a>

Use **JsonConvert** class in **Newtosoft.json** to deserialize the JSON string. The **DeserializeObject <ObservableCollection <ExpandoObject>>** method call returns a simple object instance.

```csharp
private bool IsValidJson(string strInput)
{
   if (string.IsNullOrWhiteSpace(strInput)) { return false; }
   strInput = strInput.Trim();
   if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || 
       (strInput.StartsWith("[") && strInput.EndsWith("]"))) 
   {
       try
       {
          var obj = JToken.Parse(strInput);
          return true;
       }
       catch (JsonReaderException jex)
       {
          Console.WriteLine(jex.Message);
          return false;
       }
       catch (Exception ex) 
       {
          Console.WriteLine(ex.ToString());
          return false;
       }
   }
   else
   {
       return false;
   }
}

private async void GetDataAsync(string json)
{
    Data = null;
    XBindingPath = string.Empty;
    YBindingPath = string.Empty;
    string jsonString = json;

    Uri uriResult;
    bool result = Uri.TryCreate(jsonString, UriKind.Absolute, out uriResult) && 
         (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

    if (result)
    {
        using (HttpClient httpClient = new HttpClient()) {
           jsonString = await httpClient.GetStringAsync(jsonString);
        }
     }
            
     if (IsValidJson(jsonString))
     {
         items = JsonConvert.DeserializeObject<ObservableCollection<ExpandoObject>>(jsonString);
         Data = ToDataTable(items);
         GenerateXYColumns();
     }
     else
     {
         Data = null;
     }
}
```

## <a name="table">Convert a dynamic object to a data table</a>

Convert the processed JSON data into a data table. Refer to the following code.

```csharp
DataTable ToDataTable(IEnumerable items)
{
    if (!items.Any()) return null;

    var table = new DataTable();
    bool isFirst = true;

    items.Cast<Idictionary<string, object>>().ToList().ForEach(x =>
    {
        if (isFirst)
        {
            foreach (var key in x.Keys)
            {
                table.Columns.Add(new DataColumn(key, x[key].GetType()));
            }
                   
            isFirst = false;
        }
        table.Rows.Add(x.Values.ToArray());
    });
            
    return table;
}
```

## <a name="beautiful">Create beautiful charts</a>

With the JSON data converted into a data table, it is ready to be mapped into the WPF Charts control. You can now easily plot the values of the data table on different types of charts.

The following code snippet demonstrates how to create a bar chart from the data table.

```xml
<chart:SfChart >
 <chart:SfChart.PrimaryAxis>
  <chart:CategoryAxis LabelPlacement=”BetweenTicks” 
                      ShowGridLines=”False” />
 </chart:SfChart.PrimaryAxis>

 <chart:SfChart.SecondaryAxis>
  <chart:NumericalAxis/>
 </chart:SfChart.SecondaryAxis>

 <chart:FastColumnBitmapSeries ItemsSource=”{Binding Data}” 
                               XbindingPath=”{Binding XbindingPath}”
                               YbindingPath=”{Binding YbindingPath}” />
</chart:SfChart>
```
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/04/Loading-JSON-Data-from-a-URL-1.gif" alt="Loading JSON Data from a URL" style="width:100%">

  <figcaption>Loading JSON Data from a URL</figcaption>

</figure>

## Exporting charts

You can also export charts to popular image formats like PNG and JPEG. Refer to the following code.

```csharp
if (chart != null)
{
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.FileName = “Untitled”;
    sfd.Filter = “JPEG(*.jpg,*.jpeg)|*.jpg;*.jpeg|Gif (*.gif)|*.gif|PNG(*.png)|*.png|Bitmap(*.bmp)|*.bmp|All files (*.*)|*.*”;
    if (sfd.ShowDialog() == true)
    {
        using (Stream fs = sfd.OpenFile())
        {
            chart.Save(fs, new JpegBitmapEncoder());
        }
    }
}
```
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/04/Exporting-Chart-to-Image-1.gif" alt="Exporting Chart to Image" style="width:100%">

  <figcaption>Exporting Chart to Image</figcaption>

</figure>

## Resource

For more information, refer to the project [Visualize JSON Data in WPF Charts](https://github.com/SyncfusionExamples/Visualize-JSON-Data-Quickly-Using-WPF-Chart "Visualize JSON Data in WPF Charts GitHub demo") on GitHub.

## Conclusion

Thanks for reading! In this blog, we have seen how to use the [Syncfusion Charts](https://www.syncfusion.com/wpf-controls/charts "Syncfusion WPF Charts") control to visualize JSON data in a WPF application. Try out the steps provided in this blog post and create beautiful charts.

To find detailed explanations of each feature in the Charts control with code examples, refer to this [documentation](https://help.syncfusion.com/wpf/charts/overview "Getting started with WPF Charts").

Please feel free to share your feedback or ask questions in the comments section below. You can also contact us through our [support forum](https://www.syncfusion.com/forums "Syncfusion Support Forum"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback/home "Syncfusion Feedback Portal"). We are happy to assist you!

## Related blogs

- [Seamlessly Load Data from Different Data Sources into WPF Charts](https://www.syncfusion.com/blogs/post/different-data-source-wpf-charts.aspx "Blog: Seamlessly Load Data from Different Data Sources into WPF Charts")
- [Give Your WPF Application a Fresh Look with New Windows 11 Themes](https://www.syncfusion.com/blogs/post/give-your-wpf-application-a-fresh-look-with-new-windows-11-themes.aspx "Blog: Give Your WPF Application a Fresh Look with New Windows 11 Themes")
- [Easily Create Repeating or Recurring Appointments Using WPF Scheduler](https://www.syncfusion.com/blogs/post/easily-create-repeating-or-recurring-appointments-using-wpf-scheduler.aspx "Blog: Easily Create Repeating or Recurring Appointments Using WPF Scheduler")
- [Creating an Organizational Chart Using the WPF Diagram Control: An Overview](https://www.syncfusion.com/blogs/post/creating-an-organizational-chart-using-the-wpf-diagram-control-an-overview.aspx "Blog: Creating an Organizational Chart Using the WPF Diagram Control: An Overview")