Introduction
Pretty excited while writing this article as it’s one of the favorite topics for me. Before jumping into working with JSON, let’s first understand what it is.
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999.
What is JSON?
- JSON stands for JavaScript Object Notation
- JSON is a format to exchange & store data across platforms.
- JSON is the best alternative to XML
- JSON stores values in the key/value pair format.
- XML is expressed in more words than JSON. Hence, JSON is faster to write for programmers.
- JSON is lightweight and easy to write compared to XML.
- We can store values as key/value pair in JSON. Whereas, in XML, we have to store values between opening and closing tags.
Working with JSON in ASP.NET
JSON follows syntax based on
JavaScript and it cannot be processed the same way by
C#.
In order to work with JSON in ASP.NET or C#, there are three methods.
- Using a free library, which would do all the complex work for you.
- Working with DataContracts that are built-in to the .NET framework.
- Writing your own “parser” for converting JSON into suitable format required.
In this article, I have used the free library named – JSON.NET. You can add this library to your project using the NuGet package manager. If you are not sure about adding the library, please refer to this article –
Adding references using NuGet packages
Code Snippets
- public JObject ReadJSONData(string jsonFilename)
- {
- try
- {
- JObject jObject;
-
- using (StreamReader file = System.IO.File.OpenText(jsonFilename))
- using (JsonTextReader reader = new JsonTextReader(file))
- {
- jObject = (JObject)JToken.ReadFrom(reader);
- }
- return jObject;
- }
- catch (Exception ex)
- {
- Console.WriteLine("Error Occurred : " + ex.Message);
- return null;
- }
- }
-
-
- JObject jObject = ReadJSONData(jsonFilename);
- for (int i = 0; i < jObject["employee"].Count(); i++)
- {
-
- }
Example of JSON file
- {
- "employee": [{
- "name": "Shankar",
- "empid": "1",
- "department": "Design",
- }, {
- "name": "Ashish",
- "empid": "2",
- "department": "Testing",
- }, {
- "name": "Dipendra",
- "empid": "3",
- "department": "Development",
- }]
- }
I hope you enjoyed this article. Keep exploring and using JSON with ASP.NET. Let me know in case if you feel there is an issue with the article or if you didn’t follow any part of it.
What do you think?
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.
Read more articles on ASP.NET