Like for share this blog post:
0 comments
Overview and Links
This posts shows how to parse JSON using C# and no external libraries. You can download the full source code and Visual Studio project (VS 2013 or higher) and a compiled binary for testing with
- JsonTutorial Source Code [cdn.kalebklein.com] (.zip format)
- JsonTutorial Example App [cdn.kalebklein.com] (.zip format)
The Tutorial
Over the last year, I've moved from sorting data (settings and such) from XML to JSON. I feel JSON is a much cleaner markup than XML. While both can be a bit complex the bigger the file, parsing JSON in C# is a bit easier than XML.
For example, in XML, you'd have something a bit like this:
<?xml version="1.0" encoding="utf-8"?> <myxml> <users> <user> <item type="username" value="MyUsername" /> <item type="name">John Doe</item> </user> <user> <item type="username" value="MyUsername2" /> <item type="name">Jane Doe</item> </user> </users> </myxml>
Each piece would be a node, and nodes can have child nodes, and you have to parse them all. (Or so I've experienced). If you have a big XML file, this can be a bit much. Now, let's take a look at the same thing with JSON
{ "users": [ { "username": "MyUsername", "name": "John Doe" }, { "username": "MyUsername2", "name": "Jane Doe" } ] }
Here, each item can be one of two things, an array, or an object. An object is denoted by { } while an array is denoted by [ ]. JSON is just a collection of key/value pairs that are either an object or an array. While objects are denoted with { }, they can also be strings, booleans, or numbers (int, double) or C#'s Version (if you parse it to be that way).
Parsing JSON in C# natively requires adding a reference to System.Web.Extensions. For the sake of simple parsing, we'll be using the JavaScriptSerializer class. Let's say, for example, this JSON code is in a file called users.json. We'll need to read the file, but we also need to create a skeleton class to get this info and hold it. Let's do that now.
public class User { public string username { get; set; } public string name { get; set; } } public class JsonData { public List<User> users { get; set; } }
We'll be referencing JsonData to get the users, since the users node is an array, we'll make sure it's placed into a list, which we can loop through or call from. Now, let's read the file and parse the JSON into a usable object
public class Program { public JsonData data; public static void Main(string[] args) { Program p = new Program(); p.parse("users.json"); // Call the parse method } public function parse(string filename) { // the using function here will close all streams for us // a sort of convenience method using(var reader = new StreamReader(File.OpenRead(filename))) { // Desrialize JSON text into a JsonData instance. Our class's data variable data = new JavaScriptSerializer().Deserialize<JsonData>(reader.ReadToEnd()); } } }
Now the JSON file has been parsed and it's data placed into the JsonData object: data. Let's loop through our users, and print out some data
... public static void Main(string[] args) { Program p = new Program(); p.parse(); // Call the parse method // loop through. We'll use a foreach loop, // since we don't need to reference indices // JsonData has a users property, it's a List<T>, so we can loop through it foreach(var user in p.data.users) { Console.WriteLine(string.Format("Username: {0}\r\nName: {1}\r\n\r\n", user.username, user.name)); } } ...
We can also add a new user to this list, and save the results to the JSON file, let's do that
... public static void Main(string[] args) { ... // Add new user to users list p.data.users.Add(new User() { username = "MyUsername3", name = "Jack Doe" }); // Let's commit changes to JSON file p.write("users.json"); } ... public void write(string filename) { // We'll be using the using statement again for our filestream using(var writer = new StreamWriter(File.Open(filename, FileMode.OpenOrCreate, FileAccess.Write))) { // We need to serialize our data into JSON format var json = new JavaScriptSerializer().Serialize(data); // write to file writer.Write(json); } } ...
This will output the following:
{ "users": [ { "username":"MyUsername", "name":"John Doe" }, { "username":"MyUsername2", "name":"Jane Doe" }, { "username":"MyUsername3", "name":"Jack Doe" } ] }
It won't look like this as JavaScriptSerializer doesn't add tabs and new lines to it's JSON output, but this is the output
That's pretty much out parsing and converting objects to JSON works in C# using the built in JavaScriptSerializer. There are other libraries such as the excellent Json.NET library [www.newtonsoft.com], but if you don't want to add external libraries to your projects, this is a good way to implement this feature. You can also parse JSON files over the Internet, provided you get the file's contents prior to parsing.
Emoticons you can use