Home >Backend Development >C++ >How to Convert a C# Dictionary to a JSON String Using Json.NET?

How to Convert a C# Dictionary to a JSON String Using Json.NET?

Susan Sarandon
Susan SarandonOriginal
2025-01-14 13:41:44497browse

How to Convert a C# Dictionary to a JSON String Using Json.NET?

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!

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