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

Time:04-18

I have a JSON file that looks like this:

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

At some point in my code, I will be building the key, and I want to get the value for that key. So for example I will build 0101 and I want to get the 1 from the configuration above. This is what I have (that doesn't work):

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

I can't do config[fullKey] to get my value. What would be the best way to go on reading these values?

CodePudding user response:

Using System.Text.Json you can accomplish what you're looking for with the following:

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

Without System.Text.Json you can simply modify your code:

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