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. 

{  
  "id": 123,  
  "name": "Mukesh Kumar",  
  "address": {  
    "street": "El Camino Real",  
    "city": "New Delhi",  
    "zipcode": 95014  
  },  
  "experiences": [  
    {  
      "companyid": 77,  
      "companyname": "Mind Tree LTD"  
    },  
    {  
      "companyid": 89,  
      "companyname": "TCS"  
    },  
    {  
      "companyid": 22,  
      "companyname": "Hello World LTD"  
    }  
  ],  
  "phoneNumber": 9988664422,  
  "role": "Developer"  
}   

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.

Newtonsoft-json

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

Newtonsoft Json reference

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

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. 

private void GetUserDetails()  
{  
    var json = File.ReadAllText(jsonFile);  
    try  
    {  
        var jObject = JObject.Parse(json);  
  
        if (jObject != null)  
        {  
            Console.WriteLine("ID :" + jObject["id"].ToString());  
            Console.WriteLine("Name :" + jObject["name"].ToString());  
  
            var address = jObject["address"];  
            Console.WriteLine("Street :" + address["street"].ToString());  
            Console.WriteLine("City :" + address["city"].ToString());  
            Console.WriteLine("Zipcode :" + address["zipcode"]);  
            JArray experiencesArrary = (JArray)jObject["experiences"];  
            if (experiencesArrary != null)  
            {  
                foreach (var item in experiencesArrary)  
                {  
                    Console.WriteLine("company Id :" + item["companyid"]);  
                    Console.WriteLine("company Name :" + item["companyname"].ToString());  
                }  
  
            }  
            Console.WriteLine("Phone Number :" + jObject["phoneNumber"].ToString());  
            Console.WriteLine("Role :" + jObject["role"].ToString());  
  
        }  
    }  
    catch (Exception)  
    {  
  
        throw;  
    }  
}  

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. 

private void AddCompany()  
{  
    Console.WriteLine("Enter Company ID : ");  
    var companyId = Console.ReadLine();  
    Console.WriteLine("\nEnter Company Name : ");  
    var companyName = Console.ReadLine();  
  
    var newCompanyMember = "{ 'companyid': " + companyId + ",  
    'companyname': '" + companyName + "'}";  
    try  
    {  
        var json = File.ReadAllText(jsonFile);  
var jsonObj = JObject.Parse(json);  
var experienceArrary = jsonObj.GetValue("experiences") as JArray;  
var newCompany = JObject.Parse(newCompanyMember);  
experienceArrary.Add(newCompany);  
  
        jsonObj["experiences"] = experienceArrary;  
        string newJsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj,  
                               Newtonsoft.Json.Formatting.Indented);  
File.WriteAllText(jsonFile, newJsonResult);  
    }  
    catch (Exception ex)  
    {  
        Console.WriteLine("Add Error : " + ex.Message.ToString());  
    }  
} 

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. 

private void UpdateCompany()  
{  
    string json = File.ReadAllText(jsonFile);  
  
    try  
    {  
        var jObject = JObject.Parse(json);  
        JArray experiencesArrary = (JArray)jObject["experiences"];  
        Console.Write("Enter Company ID to Update Company : ");  
        var companyId = Convert.ToInt32(Console.ReadLine());  
  
        if (companyId > 0)  
        {  
            Console.Write("Enter new company name : ");  
            var companyName = Convert.ToString(Console.ReadLine());  
  
            foreach (var company in experiencesArrary.Where(obj => obj["companyid"].Value<int>() == companyId))  
            {  
                company["companyname"] = !string.IsNullOrEmpty(companyName) ? companyName : "";  
            }  
  
            jObject["experiences"] = experiencesArrary;  
            string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);  
            File.WriteAllText(jsonFile, output);  
        }  
        else  
        {  
            Console.Write("Invalid Company ID, Try Again!");  
            UpdateCompany();  
        }  
    }  
    catch (Exception ex)  
    {  
  
        Console.WriteLine("Update Error : " + ex.Message.ToString());  
    }  
}   

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

private void DeleteCompany()  
{  
    var json = File.ReadAllText(jsonFile);  
    try  
    {  
        var jObject = JObject.Parse(json);  
        JArray experiencesArrary = (JArray)jObject["experiences"];  
        Console.Write("Enter Company ID to Delete Company : ");  
        var companyId = Convert.ToInt32(Console.ReadLine());  
  
        if (companyId > 0)  
        {  
            var companyName = string.Empty;  
            var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value<int>() == companyId);  
  
            experiencesArrary.Remove(companyToDeleted);  
  
            string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);  
            File.WriteAllText(jsonFile, output);  
        }  
        else  
        {  
            Console.Write("Invalid Company ID, Try Again!");  
            UpdateCompany();  
        }  
    }  
    catch (Exception)  
    {  
  
        throw;  
    }  
}   

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

using Newtonsoft.Json.Linq;  
using System;  
using System.IO;  
using System.Linq;  
  
namespace JsonAddAndUpdate  
{  
    class Program  
    {  
        private string jsonFile = @"C:\Users\mk9\Documents\visual studio 2015\Projects\JsonAddAndUpdate\JsonAddAndUpdate\user.json";  
        private void AddCompany()  
        {  
            Console.WriteLine("Enter Company ID : ");  
            var companyId = Console.ReadLine();  
            Console.WriteLine("\nEnter Company Name : ");  
            var companyName = Console.ReadLine();  
  
            var newCompanyMember = "{ 'companyid': " + companyId + ", 'companyname': '" + companyName + "'}";  
            try  
            {  
                var json = File.ReadAllText(jsonFile);  
                var jsonObj = JObject.Parse(json);  
                var experienceArrary = jsonObj.GetValue("experiences") as JArray;  
                var newCompany = JObject.Parse(newCompanyMember);  
                experienceArrary.Add(newCompany);  
  
                jsonObj["experiences"] = experienceArrary;  
                string newJsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);  
                File.WriteAllText(jsonFile, newJsonResult);  
            }  
            catch (Exception ex)  
            {  
                Console.WriteLine("Add Error : " + ex.Message.ToString());  
            }  
        }  
  
        private void UpdateCompany()  
        {  
            string json = File.ReadAllText(jsonFile);  
  
            try  
            {  
                var jObject = JObject.Parse(json);  
                JArray experiencesArrary = (JArray)jObject["experiences"];  
                Console.Write("Enter Company ID to Update Company : ");  
                var companyId = Convert.ToInt32(Console.ReadLine());  
  
                if (companyId > 0)  
                {  
                    Console.Write("Enter new company name : ");  
                    var companyName = Convert.ToString(Console.ReadLine());  
  
                    foreach (var company in experiencesArrary.Where(obj => obj["companyid"].Value<int>() == companyId))  
                    {  
                        company["companyname"] = !string.IsNullOrEmpty(companyName) ? companyName : "";  
                    }  
  
                    jObject["experiences"] = experiencesArrary;  
                    string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);  
                    File.WriteAllText(jsonFile, output);  
                }  
                else  
                {  
                    Console.Write("Invalid Company ID, Try Again!");  
                    UpdateCompany();  
                }  
            }  
            catch (Exception ex)  
            {  
  
                Console.WriteLine("Update Error : " + ex.Message.ToString());  
            }  
        }  
  
        private void DeleteCompany()  
        {  
            var json = File.ReadAllText(jsonFile);  
            try  
            {  
                var jObject = JObject.Parse(json);  
                JArray experiencesArrary = (JArray)jObject["experiences"];  
                Console.Write("Enter Company ID to Delete Company : ");  
                var companyId = Convert.ToInt32(Console.ReadLine());  
  
                if (companyId > 0)  
                {  
                    var companyName = string.Empty;  
                    var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value<int>() == companyId);  
  
                    experiencesArrary.Remove(companyToDeleted);  
  
                    string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);  
                    File.WriteAllText(jsonFile, output);  
                }  
                else  
                {  
                    Console.Write("Invalid Company ID, Try Again!");  
                    UpdateCompany();  
                }  
            }  
            catch (Exception)  
            {  
  
                throw;  
            }  
        }  
  
        private void GetUserDetails()  
        {  
            var json = File.ReadAllText(jsonFile);  
            try  
            {  
                var jObject = JObject.Parse(json);  
  
                if (jObject != null)  
                {  
                    Console.WriteLine("ID :" + jObject["id"].ToString());  
                    Console.WriteLine("Name :" + jObject["name"].ToString());  
  
                    var address = jObject["address"];  
                    Console.WriteLine("Street :" + address["street"].ToString());  
                    Console.WriteLine("City :" + address["city"].ToString());  
                    Console.WriteLine("Zipcode :" + address["zipcode"]);  
                    JArray experiencesArrary = (JArray)jObject["experiences"];  
                    if (experiencesArrary != null)  
                    {  
                        foreach (var item in experiencesArrary)  
                        {  
                            Console.WriteLine("company Id :" + item["companyid"]);  
                            Console.WriteLine("company Name :" + item["companyname"].ToString());  
                        }  
  
                    }  
                    Console.WriteLine("Phone Number :" + jObject["phoneNumber"].ToString());  
                    Console.WriteLine("Role :" + jObject["role"].ToString());  
  
                }  
            }  
            catch (Exception)  
            {  
  
                throw;  
            }  
        }  
        static void Main(string[] args)  
        {  
            Program objProgram = new JsonAddAndUpdate.Program();  
  
            Console.WriteLine("Choose Your Options : 1 - Add, 2 - Update, 3 - Delete, 4 - Select \n");  
            var option = Console.ReadLine();  
            switch (option)  
            {  
                case "1":  
                    objProgram.AddCompany();  
                    break;  
                case "2":  
                    objProgram.UpdateCompany();  
                    break;  
                case "3":  
                    objProgram.DeleteCompany();  
                    break;  
                case "4":  
                    objProgram.GetUserDetails();  
                    break;  
                default:  
                    Main(null);  
                    break;  
            }  
            Console.ReadLine();  
  
        }  
    }  
}  

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.