Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading