Michael Codeaholic Michael Codeaholic - 5 months ago 59
JSON Question

Deserialize Json.net JSON File directly to a C# dictionary type?

Is there a way using JSON.NET to deserialize a file type directly to a C# dictionary type?

For example:

using (StreamReader file = File.OpenText(myFileName))
Dictionary<string, int> mydictionary = new Dictionary<string, string>();

JsonSerializer serializer = new JsonSerializer();
//is there a json.net format to make the next line work
mydictionary = (JSONParameters)serializer.Deserialize(file, typeof(JSONParameters));

//return mydictionary;

I said "FILE" not dictionary to dictionary...Learn to READ!


You can use JsonConvert.DeserializeObject<> for that:

var text = File.ReadAllText(myFileName);
mydictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(text);