Kaleb Klein

JSON Parsing in C#

Created: Aug 05th, 2016, 10:47:15 PM UTC (7 years ago)

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


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:
Code Language: XML
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <myxml>
  3. <users>
  4. <user>
  5. <item type="username" value="MyUsername" />
  6. <item type="name">John Doe</item>
  7. </user>
  8. <user>
  9. <item type="username" value="MyUsername2" />
  10. <item type="name">Jane Doe</item>
  11. </user>
  12. </users>
  13. </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

Code Language: Javascript
  1. {
  2. "users": [
  3. {
  4. "username": "MyUsername",
  5. "name": "John Doe"
  6. },
  7. {
  8. "username": "MyUsername2",
  9. "name": "Jane Doe"
  10. }
  11. ]
  12. }

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.

Code Language: C#
  1. public class User
  2. {
  3. public string username { get; set; }
  4. public string name { get; set; }
  5. }
  6.  
  7. public class JsonData
  8. {
  9. public List<User> users { get; set; }
  10. }

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

Code Language: C#
  1. public class Program
  2. {
  3. public JsonData data;
  4.  
  5. public static void Main(string[] args)
  6. {
  7. Program p = new Program();
  8. p.parse("users.json"); // Call the parse method
  9. }
  10.  
  11. public function parse(string filename)
  12. {
  13. // the using function here will close all streams for us
  14. // a sort of convenience method
  15. using(var reader = new StreamReader(File.OpenRead(filename)))
  16. {
  17. // Desrialize JSON text into a JsonData instance. Our class's data variable
  18. data = new JavaScriptSerializer().Deserialize<JsonData>(reader.ReadToEnd());
  19. }
  20. }
  21. }

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

Code Language: C#
  1. ...
  2. public static void Main(string[] args)
  3. {
  4. Program p = new Program();
  5. p.parse(); // Call the parse method
  6.  
  7. // loop through. We'll use a foreach loop,
  8. // since we don't need to reference indices
  9. // JsonData has a users property, it's a List<T>, so we can loop through it
  10. foreach(var user in p.data.users)
  11. {
  12. Console.WriteLine(string.Format("Username: {0}\r\nName: {1}\r\n\r\n", user.username, user.name));
  13. }
  14. }
  15. ...

We can also add a new user to this list, and save the results to the JSON file, let's do that

Code Language: C#
  1. ...
  2. public static void Main(string[] args)
  3. {
  4. ...
  5. // Add new user to users list
  6. p.data.users.Add(new User()
  7. {
  8. username = "MyUsername3",
  9. name = "Jack Doe"
  10. });
  11.  
  12. // Let's commit changes to JSON file
  13. p.write("users.json");
  14. }
  15. ...
  16. public void write(string filename)
  17. {
  18. // We'll be using the using statement again for our filestream
  19. using(var writer = new StreamWriter(File.Open(filename, FileMode.OpenOrCreate, FileAccess.Write)))
  20. {
  21. // We need to serialize our data into JSON format
  22. var json = new JavaScriptSerializer().Serialize(data);
  23.  
  24. // write to file
  25. writer.Write(json);
  26. }
  27. }
  28. ...

This will output the following:
Code Language: Javascript
  1. {
  2. "users": [
  3. {
  4. "username":"MyUsername",
  5. "name":"John Doe"
  6. },
  7. {
  8. "username":"MyUsername2",
  9. "name":"Jane Doe"
  10. },
  11. {
  12. "username":"MyUsername3",
  13. "name":"Jack Doe"
  14. }
  15. ]
  16. }

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.


Leave a comment down below
(Required)
(Required) - For avatar image in comments area


BBCode tags you can use: [url] [code] [img] [p] [b] [i] [u] [s] [o] [size] [color] [center] [quote] /// What is BBCode?
Emoticons you can use
0
Comments


Google+

Archive

Ads