Home >Backend Development >C++ >How to Convert a C# Dictionary to a JSON String?

How to Convert a C# Dictionary to a JSON String?

Barbara Streisand
Barbara StreisandOriginal
2025-01-14 13:52:45122browse

How to Convert a C# Dictionary to a JSON String?

Convert dictionary to JSON string in C#

Question:

You have a dictionary and need to convert it to a JSON string. How can I implement this conversion in C#?

Solution:

An efficient way to convert a dictionary to JSON in C# is to use the Json.NET library. This library provides extensive support for JSON manipulation and serialization. Here's how to accomplish the conversion using Json.NET:

<code class="language-csharp">using Newtonsoft.Json;

var myDictionary = new Dictionary<int, List<int>> { { 1, new List<int> { 2, 3 } }, { 4, new List<int> { 5, 6 } } };

var jsonString = JsonConvert.SerializeObject(myDictionary);</code>

The JsonConvert.SerializeObject method takes your dictionary as input and produces a JSON string containing the serialized representation. You can then use this JSON string for various purposes, such as sending it over the network or storing it in a file.

Note that you do not have to limit the dictionary to a specific type; Json.NET handles dictionaries of all kinds of key-value pairs efficiently.

The above is the detailed content of How to Convert a C# Dictionary to a JSON String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn