I want to convert my Dictionary<int,List<int>>
to JSON string. Does anyone know how to achieve this in C#?
相关问题
- Jackson Deserialization not calling deserialize on
- Sorting 3 numbers without branching [closed]
- How to maintain order of key-value in DataFrame sa
- Graphics.DrawImage() - Throws out of memory except
- StackExchange API - Deserialize Date in JSON Respo
Simple One-Line Answer
(
using System.Web.Script.Serialization
)This code will convert any
Dictionary<Key,Value>
toDictionary<string,string>
and then serialize it as a JSON string:It is worthwhile to note that something like
Dictionary<int, MyClass>
can also be serialized in this way while preserving the complex type/object.Explanation (breakdown)
You can replace the variable
yourDictionary
with your actual variable.We do this, because both the Key and Value has to be of type string, as a requirement for serialization of a
Dictionary
.In Asp.net Core use:
You can use
System.Web.Script.Serialization.JavaScriptSerializer
:Serializing data structures containing only numeric or boolean values is fairly straightforward. If you don't have much to serialize, you can write a method for your specific type.
For a
Dictionary<int, List<int>>
as you have specified, you can use Linq:But, if you are serializing several different classes, or more complex data structures, or especially if your data contains string values, you would be better off using a reputable JSON library that already knows how to handle things like escape characters and line breaks. Json.NET is a popular option.
It seems a lot of different libraries and what not have seem to come and go over the previous years. However as of April 2016, this solution worked well for me. Strings easily replaced by ints.
TL/DR; Copy this if that's what you came here for:
Two import points. First, be sure to add System.Runtime.Serliazation as a reference in your project inside Visual Studio's Solution Explorer. Second, add this line,
at the top of the file with the rest of your usings, so the
DataContractJsonSerializer
class can be found. This blog post has more information on this method of serialization.Data Format (Input / Output)
My data is a dictionary with 3 strings, each pointing to a list of strings. The lists of strings have lengths 3, 4, and 1. The data looks like this:
The output written to file will be on one line, here is the formatted output:
Sorry if the syntax is the tiniest bit off, but the code I'm getting this from was originally in VB :)