Michael Codeaholic Michael Codeaholic - 1 year ago 235
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!

Answer Source

You can use JsonConvert.DeserializeObject<> for that:

var text = File.ReadAllText(myFileName);
mydictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(text);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download