1

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;
    }
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • You can try with: `JsonConvert.DeserializeObject>(file);` – Hackerman Sep 16 '16 at 20:14
  • 2
    Possible duplicate of [How can I deserialize JSON to a simple Dictionary in ASP.NET?](http://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net) – Heretic Monkey Sep 16 '16 at 20:22
  • What exactly is your question? It appears that you *are already* deserializing your `JSONParameters` from a file, so why is that not working? – dbc Sep 16 '16 at 20:51

1 Answers1

8

You can use JsonConvert.DeserializeObject<> for that:

var text = File.ReadAllText(myFileName);
mydictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(text);
Nico
  • 3,542
  • 24
  • 29
  • His dictionary was once declared as string, int and once as string, string if you look closely... Thanks for the downvote. And in my opinion, my answer is valid as he could use `JsonConvert.DeserializeObject<>` with the typ argument. – Nico Sep 17 '16 at 04:54
  • Your answer is correct. The other guy doesn't know how to read. I did not know that you could read the file is plain text but have it interpreted as a dictionary type. – Michael Codeaholic Sep 19 '16 at 12:15