如何在 C# 中读取一个简单的 JSON 文件?

How can I read a simple JSON file in C#?

我有一个 JSON 文件,如下所示:

{
    "0101": 1,
    "0102": 2,
    "0201": 3,
    "0202": 4,
    "0301": 5,
    "0302": 6,
    "0401": 7,
    "0402": 8
}

在我的代码中的某个时刻,我将构建密钥,并且我想获取该密钥的值。因此,例如我将构建 0101 并且我想从上面的配置中获取 1 。这就是我所拥有的(不起作用):

using (StreamReader sr = new StreamReader("file_config.json"))
{
    string json = sr.ReadToEnd();
    object config = JsonConvert.DeserializeObject(json);
    //string fullKey = process to construct the key...
    var ID = config[fullKey]
}

我无法config[fullKey]获得我的价值。继续阅读这些值的最佳方式是什么?

使用 System.Text.Json 您可以通过以下方式完成您正在寻找的内容:

var config = JsonSerializer.Deserialize<Dictionary<string, int>>(json);
var ID = config[fullKey];

使用Newtonsoft.Json:

var config = JsonConvert.DeserializeObject<Dictionary<string, int>>(json);