Mohanapriya R Mohanapriya R
Updated date May 18, 2024
In this article, we will explore the JSON-to-string conversion in C# with sample program and output.

How to Convert JSON to Strings in C#?

C# provides an easy way to work with JSON through its Newtonsoft.Json library, also known as JSON.NET. We will use JSON.NET to convert JSON objects to strings in C#.

Installing JSON.NET:

Please ensure you have the JSON.NET library installed in your project. You can install it using "NuGet Package Manager" with the following command:

Install-Package Newtonsoft.Json

The below C# program converts a JSON object to a string,

using System;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        // Creating a sample JSON object
        var jsonObject = new
        {
            Name = "Priya",
            Age = 30,
            Occupation = "Software Developer"
        };

        // Converting JSON object to a string
        string jsonString = JsonConvert.SerializeObject(jsonObject);

        // Displaying the result
        Console.WriteLine("JSON to String Conversion Output:");
        Console.WriteLine(jsonString);
    }
}

In this program, we first create a sample JSON object using an anonymous type in C#. The JsonConvert.SerializeObject method from JSON.NET is then used to convert this object into a JSON-formatted string. Finally, the converted string is printed to the console.

Output:

JSON to String Conversion Output:
{"Name":"Priya","Age":30,"Occupation":"Software Developer"}

Comments (0)

There are no comments. Be the first to comment!!!