-3

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?

plasmy
  • 99
  • 3
  • 9
  • 32
  • Does this answer your question? [json deserialization to C# with dynamic keys](https://stackoverflow.com/questions/65727513/json-deserialization-to-c-sharp-with-dynamic-keys) – Charlieface Apr 18 '22 at 02:50

1 Answers1

3

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

Using Newtonsoft.Json:

var config = JsonConvert.DeserializeObject<Dictionary<string, int>>(json);
Ergis
  • 1,105
  • 1
  • 7
  • 18
emagers
  • 841
  • 7
  • 13