将Json.net JSON文件直接反序列化为C#字典类型?

时间:2016-09-16 20:11:34

标签: c# json json.net

有没有办法使用JSON.NET将文件类型直接反序列化为C#字典类型?

例如:

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;
    }

我说&#34; FILE&#34;不是字典到字典...学会阅读!

1 个答案:

答案 0 :(得分:3)

您可以使用JsonConvert.DeserializeObject<>

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