Visualize JSON Data Quickly Using WPF Charts
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (175).NET Core  (29).NET MAUI  (208)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (220)BoldSign  (15)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (67)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (101)Streamlit  (1)Succinctly series  (131)Syncfusion  (920)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (37)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (151)Chart  (132)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (633)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (41)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (508)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (11)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (597)What's new  (333)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Visualize JSON Data Quickly Using WPF Charts

Visualize JSON Data Quickly Using WPF Charts

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 control. This can be achieved with the following easy steps:

  1. Process JSON data.
  2. Deserialize the JSON data to a dynamic object.
  3. Convert the list of dynamic objects to a data table.
  4. Create beautiful charts from the data table.

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.

Fetch and Display Advanced JSON Data in WPF Charts
Fetch and Display Advanced JSON Data in WPF Charts

Process JSON data

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 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

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

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.

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

Deserialize the JSON data to dynamic object

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

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;
     }
}

Convert a dynamic object to a data table

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

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;
}

Create beautiful charts

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.

<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>
Loading JSON Data from a URL
Loading JSON Data from a URL

Exporting charts

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

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());
        }
    }
}
Exporting Chart to Image
Exporting Chart to Image

Resource

For more information, refer to the project Visualize JSON Data in WPF Charts on GitHub.

Conclusion

Thanks for reading! In this blog, we have seen how to use the Syncfusion 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.

Please feel free to share your feedback or ask questions in the comments section below. You can also contact us through our support forumsupport portal, or feedback portal. We are happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed