Jump to content

How to Create and Manipulate JSON Objects in C#


Linux Hint

Recommended Posts

Whether you are building a massively complex application or a simple console application, you might come across instances where you need to transmit the data. One of the most powerful data interchange formats is JSON. It offers a lightweight and human-readable format while supporting a complex data layout.

In this tutorial, we will learn how to use the provided C# tools and features to read and parse the data from a JSON file in a C# application.

Sample JSON File

Let us start by setting up our JSON file that we are going to use for demonstration purposes. In our case, the JSON file is as follows:

{
  "database": {
    "name": "admin",
    "type": "SQL",
    "server": "localhost:5904",
    "creds": {
      "username": "root",
      "password": "mysql"
    }
  }
}

In this case, we have a basic JSON file with nested values which allows us to demonstrate how to read an arrayed JSON file.

Install the Newtonsoft.JSON Package

In order to quickly and efficiently parse and work with JSON data in C#, we make use of a “.NET” external library. In this case, we use the Newtonsoft.JSON package to read and work with JSON data.

Before using it, we need to ensure that we have it installed. We can run the following command in the NuGet package console as follows:

Install-Package Newtonsoft.Json

This should download and allow you to access the features from the Newtonsoft JSON package.

Read and Deserialize a C# JSON File

Once we have everything ready, we can proceed and read the JSON file. We can add the source code as follows:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string jsonFilePath = "config.json";
        string jsonString;

        if (File.Exists(jsonFilePath))
        {
            jsonString = File.ReadAllText(jsonFilePath);
            Console.WriteLine(jsonString);
        }
        else
        {
            Console.WriteLine("File not found!");
        }
    }
}

In the previous example code, we start by defining the path to the JSON file. Next, we define a new variable to store the raw JSON string that we read.

Finally, we use the “File.ReadAllText” to read the JSON file.

The next step is to deserialize the JSON string. Deserializing allows us to format JSON into a valid C# object. We can do this by creating a class that represents the structure of the JSON data from the file.

An example code is as follows:

using System;
using System.IO;
using Newtonsoft.Json;
public class Creds
{
    public string Username { get; set; }
    public string Password { get; set; }
}

public class Database
{
    public string Name { get; set; }
    public string Type { get; set; }
    public string Server { get; set; }
    public Creds Creds { get; set; }
}

public class RootObject
{
    public Database Database { get; set; }
}

class Program
{
    static void Main()
    {
        string jsonFilePath = "config.json";
        string jsonString;

        if (File.Exists(jsonFilePath))
        {
            jsonString = File.ReadAllText(jsonFilePath);
            RootObject dbInfo = JsonConvert.DeserializeObject<RootObject>(jsonString);
            Console.WriteLine($"Database Name: {dbInfo.Database.Name}");
            Console.WriteLine($"Type: {dbInfo.Database.Type}");
            Console.WriteLine($"Server: {dbInfo.Database.Server}");
            Console.WriteLine($"Username: {dbInfo.Database.Creds.Username}");
            Console.WriteLine($"Password: {dbInfo.Database.Creds.Password}");
        }
        else
        {
            Console.WriteLine("File not found!");
        }
    }
}

In the given example, we define three main classes. The first is the “Credentials” class, the second is the “Database” class, and the third is the “RootObject” classes. Each class maps the structure of the JSON data and the corresponding types.

Finally, we use the “JsonConvert.DeserializedObject” method to convert the resulting JSON string from the file into a C# object.

Read the C# JSON Arrays

As you can guess, JSON data in the real world is not as simplistic as shown in the previous examples. One of the most complex features that you will encounter in JSON is the arrays or nested JSON objects.

Let us see how we can handle such a layout in C#.

In our case, we are dealing with a JSON file as follows:

[
  {
    "name": "admin",
    "type": "SQL",
    "server": "localhost:5094",
    "creds": {
      "username": "root",
      "password": "mysql"
    }
  },
  {
    "name": "users",
    "type": "MongoDB",
    "server": "localhost:5095",
    "creds": {
      "username": "root",
      "password": "postgres"
    }
  }
]

Once we define the previous code, we can proceed and deserialize the JSON file and read the file.

An example code is as follows:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;

public class Creds
{
    public string Username { get; set; }
    public string Password { get; set; }
}

public class Database
{
    public string Name { get; set; }
    public string Type { get; set; }
    public string Server { get; set; }
    public Creds Creds { get; set; }
}

class Program
{
    static void Main()
    {
        string jsonFilePath = "config.json";
        string jsonString;

        if (File.Exists(jsonFilePath))
        {
            jsonString = File.ReadAllText(jsonFilePath);
            List<Database> databases = JsonConvert.DeserializeObject<List<Database>>(jsonString);

            foreach (var db in databases)
            {
                Console.WriteLine($"Database Name: {db.Name}");
                Console.WriteLine($"Type: {db.Type}");
                Console.WriteLine($"Server: {db.Server}");
                Console.WriteLine($"Username: {db.Creds.Username}");
                Console.WriteLine($"Password: {db.Creds.Password}");
                Console.WriteLine();
            }
        }
        else
        {
            Console.WriteLine("File not found!");
        }
    }
}

You might notice that the previous program does not provide much difference than a regular JSON parsing. The main difference is that in the JsonConvert.DeserializeObject method, we convert the JSON string into a “List of Database” object where each object contains information about each array from the JSON list.

The resulting output is as follows:

Database Name: admin
Type: SQL
Server: localhost:5094
Username: root
Password: mysql

Database Name: users
Type: MongoDB
Server: localhost:5095
Username: root
Password: postgres

Conclusion

In this tutorial, we covered all the features of reading and working with JSON files in a C# application using the Newtonsoft.JSON application.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...