This article will explain how I use a simple JSON data viewer using the JavaScriptSerializer class and the System.Web.Extensions assembly.
Introduction
When using any kind of AJAX query with web method interaction, passing back a JSON string to the code behind may be the easiest way to show data client side and server side. I’ll show an example program of how to visualize the JSON data for any type of debugging or what have you.
Background
I have used the JavaScriptSerializer class in web application project so I wanted to created a desktop winform application to parse through the JSON string.
Using the Code
First step is to deserialzed the data. We will need to add a reference to the System.Web.Script.Serialztion namespace. This namespace gives you acces to the Deserialize method. I will use a Dictionary type for this example.
JavaScriptSerializer js = new JavaScriptSerializer(); try { Dictionary<string,> dic = js.Deserialize<dictionary<string,>>(txtInput.Text); TreeNode rootNode = new TreeNode("Root"); jsonExplorer.Nodes.Add(rootNode); BuildTree(dic, rootNode); } catch (ArgumentException argE) { MessageBox.Show("JSON data is not valid"); }
Next step is, since we are visualizing the data, we need a way to show it. There are many ways to do this, so I have chosen to use the TreeView control where we can represent the key/value pair for JSON string.
public void BuildTree(Dictionary<string,> dictionary, TreeNode node) { foreach (KeyValuePair<string,> item in dictionary) { TreeNode parentNode = new TreeNode(item.Key); node.Nodes.Add(parentNode); try { dictionary = (Dictionary<string,>)item.Value; BuildTree(dictionary, parentNode); } catch (InvalidCastException dicE) { try { ArrayList list = (ArrayList)item.Value; foreach (string value in list) { TreeNode finalNode = new TreeNode(value); finalNode.ForeColor = Color.Blue; parentNode.Nodes.Add(finalNode); } } catch (InvalidCastException ex) { TreeNode finalNode = new TreeNode(item.Value.ToString()); finalNode.ForeColor = Color.Blue; parentNode.Nodes.Add(finalNode); } } } }
Conclusion
For the example application I created, I pass in a JSON file/string using the OpenFileDialog class in the winform tool box to finish up the project.
License
This site along with the code is license under The Code Project Open License