Keywords: C# | JSON Serialization | Dictionary Conversion | Json.NET | System.Text.Json
Abstract: This article provides a comprehensive exploration of converting Dictionary<int,List<int>> to JSON strings in C#, focusing on Json.NET library usage and manual serialization approaches. Through comparative analysis of different methods' advantages and limitations, it offers practical guidance for developers in various scenarios, with in-depth discussion on System.Text.Json performance benefits and non-string key constraints.
Fundamentals of Dictionary Serialization
In C# programming, dictionaries as key-value pair collection data structures frequently require serialization into JSON format for data exchange or persistence. JSON (JavaScript Object Notation) serves as a lightweight data interchange format with excellent readability and cross-platform compatibility.
Json.NET Library Serialization Approach
Json.NET (Newtonsoft.Json) stands as the most popular JSON serialization library in the C# ecosystem, offering straightforward and efficient dictionary serialization capabilities. For Dictionary<int,List<int>> type dictionaries, direct usage of JsonConvert.SerializeObject() method enables seamless serialization:
Dictionary<int, List<int>> myDictionary = new Dictionary<int, List<int>>
{
{ 1, new List<int> { 1, 2, 3 } },
{ 2, new List<int> { 4, 5, 6 } }
};
string jsonString = JsonConvert.SerializeObject(myDictionary);
Compared to traditional JavaScriptSerializer, Json.NET demonstrates significant advantages. It doesn't require dictionary keys to be string types and can properly handle various complex data types, including nested collections and custom objects.
Manual Serialization Implementation
For simple data structures and specific use cases, developers may opt for manual serialization implementation. This approach avoids external dependencies but requires handling more implementation details:
string MyDictionaryToJson(Dictionary<int, List<int>> dict)
{
var entries = dict.Select(d =>
string.Format(""{0}": [{1}]", d.Key, string.Join(",", d.Value)));
return "{" + string.Join(",", entries) + "}";
}
This method's advantages include code simplicity and absence of external dependencies, making it particularly suitable for constrained environments. However, it exhibits clear limitations: inability to properly handle complex data structures containing string values, lack of automatic escaping mechanisms for special characters (such as quotes and line breaks), and poor extensibility.
System.Text.Json Performance Optimization
With the release of .NET Core 3.0, Microsoft introduced the new System.Text.Json library, specifically designed for high-performance scenarios. Compared to Json.NET, it demonstrates significant improvements in memory allocation and throughput:
var obj = new Dictionary<string, object>
{
["id"] = 43,
["title"] = "Western Union",
["isEnabled"] = true,
["tags"] = new string[] { "things", "stuff" }
};
var json = JsonSerializer.Serialize(obj);
However, System.Text.Json imposes limitations when handling non-string dictionary keys. Attempting to deserialize Dictionary<Guid, int> throws a NotSupportedException, requiring custom converter solutions:
var options = new JsonSerializerOptions();
options.Converters.Add(DictionaryJsonConverterFactory.Default);
var raw = ""49fc2162-744a-4a42-b685-ea1e30ce2a2f": 99";
var d = JsonSerializer.Deserialize<Dictionary<Guid, int>>(raw, options);
Method Selection and Best Practices
When selecting serialization methods, developers should consider the following factors:
Json.NET Suitable Scenarios: Requirements for handling complex data structures, support for multiple data types, and projects with existing Json.NET dependencies. Json.NET provides the most complete feature set and best compatibility.
Manual Serialization Suitable Scenarios: Simple data structures, numeric-only types, specific scenarios with extreme performance requirements and inability to introduce external dependencies.
System.Text.Json Suitable Scenarios: New projects, strict performance requirements, and primarily string-key dictionary processing. Although the initial learning curve is steeper, long-term performance advantages are significant.
For complex data structures containing string values, strongly recommend using mature JSON libraries as they automatically handle character escaping, encoding issues, and other complex scenarios, avoiding potential security vulnerabilities and data corruption risks.
Performance Comparison and Optimization Recommendations
In actual performance testing, System.Text.Json typically demonstrates 20-30% performance improvement over Json.NET, particularly when processing large data volumes. This performance advantage primarily stems from reduced memory allocation and optimized algorithm implementations.
For high-frequency serialization operations, recommendations include:
- Reusing
JsonSerializerOptionsinstances to avoid repeated configuration overhead - Considering source generators for fixed-structure data
- Leveraging built-in JSON serialization optimizations in ASP.NET Core applications
Through appropriate serialization scheme selection and optimization configuration, developers can achieve optimal performance while ensuring functional completeness.