To convert a dictionary to a JSON string in C#, you can use the `JsonConvert.SerializeObject` method from the `Newtonsoft.Json` library. This allows you to create a JSON string representation of the dictionary.
We can convert a dictionary to a JSON string in C# using the `JsonConvert.SerializeObject` method from the `Newtonsoft.Json` library. This example demonstrates how to declare and initialize a dictionary, use the `JsonConvert.SerializeObject` method to convert the dictionary to a JSON string, and print the resulting JSON string.
For example,
using Newtonsoft.Json;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
using Newtonsoft.Json;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Convert the dictionary to a JSON string using JsonConvert.SerializeObject
string jsonString = JsonConvert.SerializeObject(myDictionary);
// Print the resulting JSON string
Console.WriteLine("JSON string:");
Console.WriteLine(jsonString);
}
}
JSON string: {"1":"One","2":"Two","3":"Three"}
We can convert a dictionary with complex values to a JSON string in C# using the `JsonConvert.SerializeObject` method from the `Newtonsoft.Json` library. This example demonstrates how to declare and initialize a dictionary with complex values, use the `JsonConvert.SerializeObject` method to convert the dictionary to a JSON string, and print the resulting JSON string.
For example,
using Newtonsoft.Json;
.Person
with properties Name
and Age
.myDictionary
with integer keys and Person
values.using System;
using System.Collections.Generic;
using Newtonsoft.Json;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
// Declare and initialize a dictionary with complex values
Dictionary<int, Person> myDictionary = new Dictionary<int, Person>
{
{1, new Person { Name = "John", Age = 30 }},
{2, new Person { Name = "Jane", Age = 25 }}
};
// Convert the dictionary to a JSON string using JsonConvert.SerializeObject
string jsonString = JsonConvert.SerializeObject(myDictionary, Formatting.Indented);
// Print the resulting JSON string
Console.WriteLine("JSON string:");
Console.WriteLine(jsonString);
}
}
JSON string: { "1": { "Name": "John", "Age": 30 }, "2": { "Name": "Jane", "Age": 25 } }
In this tutorial, we learned How to Convert a Dictionary to a JSON String in C# language with well detailed examples.