CRUD Operation With JSON File Data In C#

This article will demonstrate how to implement CRUD functionality with JSON file in a project using C# code. 

As we know, JSON [JavaScript Object Notation] is a subset of JavaScript and is very lightweight data exchange format. Sometimes, we want to use such type of storage in a project from where we can access data very quickly. We do not want to go with creating connection and check connection availability and do not want to be dependent on another server because it’s time-consuming.

Just for example, if a project has no database connectivity and would like to store single user information, here we can use a JSON file to store such data. Therefore, this article gives you an idea how you can perform CRUD operations on JSON files and use JSON files as a database.

Implementation

For this demonstration, we will use the following JSON format. So, create a console application in Visual Studio using C# and add a JSON file named "user.json".  Add the following line of code inside the user.json file so that we can perform CRUD operation on this. 

Therefore, this JSON file contains user information like user id, name, address, experiences etc. The next code will show you the process to selecting user data, updating the existing data, inserting the new experience, and deleting the user experience. 

  1. {  
  2.   "id": 123,  
  3.   "name""Mukesh Kumar",  
  4.   "address": {  
  5.     "street""El Camino Real",  
  6.     "city""New Delhi",  
  7.     "zipcode": 95014  
  8.   },  
  9.   "experiences": [  
  10.     {  
  11.       "companyid": 77,  
  12.       "companyname""Mind Tree LTD"  
  13.     },  
  14.     {  
  15.       "companyid": 89,  
  16.       "companyname""TCS"  
  17.     },  
  18.     {  
  19.       "companyid": 22,  
  20.       "companyname""Hello World LTD"  
  21.     }  
  22.   ],  
  23.   "phoneNumber": 9988664422,  
  24.   "role""Developer"  
  25. }   

Get the user.json file path from the system to use further.

private string jsonFile = @"C:\Users\mk9\Documents\visual studio 2015\Projects\JsonAddAndUpdate\JsonAddAndUpdate\user.json";

Before you proceed further, you need to add reference for Newtonsoft.Json which is a high performance JSON framework for .NET, and which provides all the methods and properties. For more about Newtonsoft.Json, go through http://www.newtonsoft.com/json.

C#

After installing Newtonsoft.Json reference, the project will look like the following screenshot.

C#

Add the following namespace to access Newtonsoft.Json methods and properties.

  1. using Newtonsoft.Json.Linq;  

First, we will see how can we read the JSON file and access all data points from that JSON file. After reading file data, first, parse the JSON data using JObject.Parse, which will parse and return JObject. Once you get JObject, which is nothing but an array, we can directly access all data points to pass key.

To access the nested data points, we need to iterate on JObject or JArray. Following is the whole code to access all the data points from existing JSON file. 

  1. private void GetUserDetails()  
  2. {  
  3.     var json = File.ReadAllText(jsonFile);  
  4.     try  
  5.     {  
  6.         var jObject = JObject.Parse(json);  
  7.   
  8.         if (jObject != null)  
  9.         {  
  10.             Console.WriteLine("ID :" + jObject["id"].ToString());  
  11.             Console.WriteLine("Name :" + jObject["name"].ToString());  
  12.   
  13.             var address = jObject["address"];  
  14.             Console.WriteLine("Street :" + address["street"].ToString());  
  15.             Console.WriteLine("City :" + address["city"].ToString());  
  16.             Console.WriteLine("Zipcode :" + address["zipcode"]);  
  17.             JArray experiencesArrary = (JArray)jObject["experiences"];  
  18.             if (experiencesArrary != null)  
  19.             {  
  20.                 foreach (var item in experiencesArrary)  
  21.                 {  
  22.                     Console.WriteLine("company Id :" + item["companyid"]);  
  23.                     Console.WriteLine("company Name :" + item["companyname"].ToString());  
  24.                 }  
  25.   
  26.             }  
  27.             Console.WriteLine("Phone Number :" + jObject["phoneNumber"].ToString());  
  28.             Console.WriteLine("Role :" + jObject["role"].ToString());  
  29.   
  30.         }  
  31.     }  
  32.     catch (Exception)  
  33.     {  
  34.   
  35.         throw;  
  36.     }  
  37. }   

To add new data points in the existing JSON file, first, you need to create a structured data that will be added in your existing JSON object. As following code is shown, we are going to add new experience data in experiences section in JSON file. Therefore, first, we will create a JSON format data which contain your experience data. That will go and add with experience array. See the below bold code text. 

  1. private void AddCompany()  
  2. {  
  3.     Console.WriteLine("Enter Company ID : ");  
  4.     var companyId = Console.ReadLine();  
  5.     Console.WriteLine("\nEnter Company Name : ");  
  6.     var companyName = Console.ReadLine();  
  7.   
  8.     var newCompanyMember = "{ 'companyid': " + companyId + ",  
  9.     'companyname''" + companyName + "'}";  
  10.     try  
  11.     {  
  12.         var json = File.ReadAllText(jsonFile);  
  13. var jsonObj = JObject.Parse(json);  
  14. var experienceArrary = jsonObj.GetValue("experiences") as JArray;  
  15. var newCompany = JObject.Parse(newCompanyMember);  
  16. experienceArrary.Add(newCompany);  
  17.   
  18.         jsonObj["experiences"] = experienceArrary;  
  19.         string newJsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj,  
  20.                                Newtonsoft.Json.Formatting.Indented);  
  21. File.WriteAllText(jsonFile, newJsonResult);  
  22.     }  
  23.     catch (Exception ex)  
  24.     {  
  25.         Console.WriteLine("Add Error : " + ex.Message.ToString());  
  26.     }  
  27. }   

Updating the JSON file is something different from selecting and inserting. Here we need to select those data, which need to be updated. Then update that value. In the  following code, you can see first we are going to select experience data point to pass company id. Once that JSON data will be available, we can update company name. 

  1. private void UpdateCompany()  
  2. {  
  3.     string json = File.ReadAllText(jsonFile);  
  4.   
  5.     try  
  6.     {  
  7.         var jObject = JObject.Parse(json);  
  8.         JArray experiencesArrary = (JArray)jObject["experiences"];  
  9.         Console.Write("Enter Company ID to Update Company : ");  
  10.         var companyId = Convert.ToInt32(Console.ReadLine());  
  11.   
  12.         if (companyId > 0)  
  13.         {  
  14.             Console.Write("Enter new company name : ");  
  15.             var companyName = Convert.ToString(Console.ReadLine());  
  16.   
  17.             foreach (var company in experiencesArrary.Where(obj => obj["companyid"].Value<int>() == companyId))  
  18.             {  
  19.                 company["companyname"] = !string.IsNullOrEmpty(companyName) ? companyName : "";  
  20.             }  
  21.   
  22.             jObject["experiences"] = experiencesArrary;  
  23.             string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);  
  24.             File.WriteAllText(jsonFile, output);  
  25.         }  
  26.         else  
  27.         {  
  28.             Console.Write("Invalid Company ID, Try Again!");  
  29.             UpdateCompany();  
  30.         }  
  31.     }  
  32.     catch (Exception ex)  
  33.     {  
  34.   
  35.         Console.WriteLine("Update Error : " + ex.Message.ToString());  
  36.     }  
  37. }   

To remove the data points from JSON file, we can use Remove method. 

  1. private void DeleteCompany()  
  2. {  
  3.     var json = File.ReadAllText(jsonFile);  
  4.     try  
  5.     {  
  6.         var jObject = JObject.Parse(json);  
  7.         JArray experiencesArrary = (JArray)jObject["experiences"];  
  8.         Console.Write("Enter Company ID to Delete Company : ");  
  9.         var companyId = Convert.ToInt32(Console.ReadLine());  
  10.   
  11.         if (companyId > 0)  
  12.         {  
  13.             var companyName = string.Empty;  
  14.             var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value<int>() == companyId);  
  15.   
  16.             experiencesArrary.Remove(companyToDeleted);  
  17.   
  18.             string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);  
  19.             File.WriteAllText(jsonFile, output);  
  20.         }  
  21.         else  
  22.         {  
  23.             Console.Write("Invalid Company ID, Try Again!");  
  24.             UpdateCompany();  
  25.         }  
  26.     }  
  27.     catch (Exception)  
  28.     {  
  29.   
  30.         throw;  
  31.     }  
  32. }   

Following is the whole code which will help you understand step by step CRUD operation on JSON file using C#. 

  1. using Newtonsoft.Json.Linq;  
  2. using System;  
  3. using System.IO;  
  4. using System.Linq;  
  5.   
  6. namespace JsonAddAndUpdate  
  7. {  
  8.     class Program  
  9.     {  
  10.         private string jsonFile = @"C:\Users\mk9\Documents\visual studio 2015\Projects\JsonAddAndUpdate\JsonAddAndUpdate\user.json";  
  11.         private void AddCompany()  
  12.         {  
  13.             Console.WriteLine("Enter Company ID : ");  
  14.             var companyId = Console.ReadLine();  
  15.             Console.WriteLine("\nEnter Company Name : ");  
  16.             var companyName = Console.ReadLine();  
  17.   
  18.             var newCompanyMember = "{ 'companyid': " + companyId + ", 'companyname': '" + companyName + "'}";  
  19.             try  
  20.             {  
  21.                 var json = File.ReadAllText(jsonFile);  
  22.                 var jsonObj = JObject.Parse(json);  
  23.                 var experienceArrary = jsonObj.GetValue("experiences") as JArray;  
  24.                 var newCompany = JObject.Parse(newCompanyMember);  
  25.                 experienceArrary.Add(newCompany);  
  26.   
  27.                 jsonObj["experiences"] = experienceArrary;  
  28.                 string newJsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);  
  29.                 File.WriteAllText(jsonFile, newJsonResult);  
  30.             }  
  31.             catch (Exception ex)  
  32.             {  
  33.                 Console.WriteLine("Add Error : " + ex.Message.ToString());  
  34.             }  
  35.         }  
  36.   
  37.         private void UpdateCompany()  
  38.         {  
  39.             string json = File.ReadAllText(jsonFile);  
  40.   
  41.             try  
  42.             {  
  43.                 var jObject = JObject.Parse(json);  
  44.                 JArray experiencesArrary = (JArray)jObject["experiences"];  
  45.                 Console.Write("Enter Company ID to Update Company : ");  
  46.                 var companyId = Convert.ToInt32(Console.ReadLine());  
  47.   
  48.                 if (companyId > 0)  
  49.                 {  
  50.                     Console.Write("Enter new company name : ");  
  51.                     var companyName = Convert.ToString(Console.ReadLine());  
  52.   
  53.                     foreach (var company in experiencesArrary.Where(obj => obj["companyid"].Value<int>() == companyId))  
  54.                     {  
  55.                         company["companyname"] = !string.IsNullOrEmpty(companyName) ? companyName : "";  
  56.                     }  
  57.   
  58.                     jObject["experiences"] = experiencesArrary;  
  59.                     string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);  
  60.                     File.WriteAllText(jsonFile, output);  
  61.                 }  
  62.                 else  
  63.                 {  
  64.                     Console.Write("Invalid Company ID, Try Again!");  
  65.                     UpdateCompany();  
  66.                 }  
  67.             }  
  68.             catch (Exception ex)  
  69.             {  
  70.   
  71.                 Console.WriteLine("Update Error : " + ex.Message.ToString());  
  72.             }  
  73.         }  
  74.   
  75.         private void DeleteCompany()  
  76.         {  
  77.             var json = File.ReadAllText(jsonFile);  
  78.             try  
  79.             {  
  80.                 var jObject = JObject.Parse(json);  
  81.                 JArray experiencesArrary = (JArray)jObject["experiences"];  
  82.                 Console.Write("Enter Company ID to Delete Company : ");  
  83.                 var companyId = Convert.ToInt32(Console.ReadLine());  
  84.   
  85.                 if (companyId > 0)  
  86.                 {  
  87.                     var companyName = string.Empty;  
  88.                     var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value<int>() == companyId);  
  89.   
  90.                     experiencesArrary.Remove(companyToDeleted);  
  91.   
  92.                     string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);  
  93.                     File.WriteAllText(jsonFile, output);  
  94.                 }  
  95.                 else  
  96.                 {  
  97.                     Console.Write("Invalid Company ID, Try Again!");  
  98.                     UpdateCompany();  
  99.                 }  
  100.             }  
  101.             catch (Exception)  
  102.             {  
  103.   
  104.                 throw;  
  105.             }  
  106.         }  
  107.   
  108.         private void GetUserDetails()  
  109.         {  
  110.             var json = File.ReadAllText(jsonFile);  
  111.             try  
  112.             {  
  113.                 var jObject = JObject.Parse(json);  
  114.   
  115.                 if (jObject != null)  
  116.                 {  
  117.                     Console.WriteLine("ID :" + jObject["id"].ToString());  
  118.                     Console.WriteLine("Name :" + jObject["name"].ToString());  
  119.   
  120.                     var address = jObject["address"];  
  121.                     Console.WriteLine("Street :" + address["street"].ToString());  
  122.                     Console.WriteLine("City :" + address["city"].ToString());  
  123.                     Console.WriteLine("Zipcode :" + address["zipcode"]);  
  124.                     JArray experiencesArrary = (JArray)jObject["experiences"];  
  125.                     if (experiencesArrary != null)  
  126.                     {  
  127.                         foreach (var item in experiencesArrary)  
  128.                         {  
  129.                             Console.WriteLine("company Id :" + item["companyid"]);  
  130.                             Console.WriteLine("company Name :" + item["companyname"].ToString());  
  131.                         }  
  132.   
  133.                     }  
  134.                     Console.WriteLine("Phone Number :" + jObject["phoneNumber"].ToString());  
  135.                     Console.WriteLine("Role :" + jObject["role"].ToString());  
  136.   
  137.                 }  
  138.             }  
  139.             catch (Exception)  
  140.             {  
  141.   
  142.                 throw;  
  143.             }  
  144.         }  
  145.         static void Main(string[] args)  
  146.         {  
  147.             Program objProgram = new JsonAddAndUpdate.Program();  
  148.   
  149.             Console.WriteLine("Choose Your Options : 1 - Add, 2 - Update, 3 - Delete, 4 - Select \n");  
  150.             var option = Console.ReadLine();  
  151.             switch (option)  
  152.             {  
  153.                 case "1":  
  154.                     objProgram.AddCompany();  
  155.                     break;  
  156.                 case "2":  
  157.                     objProgram.UpdateCompany();  
  158.                     break;  
  159.                 case "3":  
  160.                     objProgram.DeleteCompany();  
  161.                     break;  
  162.                 case "4":  
  163.                     objProgram.GetUserDetails();  
  164.                     break;  
  165.                 default:  
  166.                     Main(null);  
  167.                     break;  
  168.             }  
  169.             Console.ReadLine();  
  170.   
  171.         }  
  172.     }  
  173. }   

Conclusion

So, we have seen how to perform CRUD operations on JSON files using C# code.

I hope this post helps you. Please put your feedback using comments which will help me improve for the next post. If you have any doubts, please ask your doubts or query in the comments section.

Up Next
    Ebook Download
    View all
    Learn
    View all