Click here to Skip to main content
13,091,369 members (71,766 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

4.3K views
8 bookmarked
Posted 12 Aug 2017

CRUD Operation with JSON File Data in C#

, 13 Aug 2017
Rate this:
Please Sign up or sign in to vote.
This article will demonstrate how to manipulate data and perform CRUD operation in JSON file using C#.

Introduction

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

As we know, JSON [JavaScript Object Notation] is a subset of JavaScript and very lightweight data exchange format. Sometimes, we want to use such type of storage in 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 which have not any database connectivity and would like to store single user information, so here we can use JSON file to store as such data. Therefore, this article gives you an idea how you can perform CRUD operation on JSON file and use JSON file as a database.

Using the Code

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 as name "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 about 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 is high performance JSON framework for .NET, which provides all the methods and properties. For more about Newtonsoft.Json, go through this link.

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

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 datapoints to pass key.

To access nested data points, we need to iterate on JObject or JArray. Following is the whole code to access all the data points from the 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 existing JSON file, first you need to create a structured data that will be added in your existing JSON object. As the 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 contains 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 needs to be updated. Then update that value. In the following code, you can see first that 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 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 operation on JSON file 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

MukeshKumarMVP
Software Developer
India India
No Biography provided

You may also be interested in...

Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170813.1 | Last Updated 13 Aug 2017
Article Copyright 2017 by MukeshKumarMVP
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid