Convert C# dictionary to JSON string using Json.NET
Converting dictionary to JSON string in C# is a common task. While it is possible to use JavaScriptSerializer, its limitations require that the dictionary must be of type <string, string>
.
For a more general solution, consider using Json.NET. This library provides a simple and efficient way to serialize dictionaries into JSON strings.
To use Json.NET, use NuGet to install the Newtonsoft.Json package. Once installed, you can easily convert the dictionary to a JSON string using the following code:
<code class="language-csharp">using Newtonsoft.Json; // ... var myDictionary = new Dictionary<int, List<string>>(); // 填充字典... string jsonString = JsonConvert.SerializeObject(myDictionary);</code>
This code will serialize the dictionary into a JSON string, which can then be used for various purposes, such as sending it to a web service or storing it in a database.
The above is the detailed content of How to Convert a C# Dictionary to a JSON String Using Json.NET?. For more information, please follow other related articles on the PHP Chinese website!