C# building a string for JSON using variables

I'm relatively new to C# and trying to deserialize a string from JSON for this value; ["format"]["tags"]["ENCODER"]

// Manually building the string works fine
string test = (dict["format"]["tags"]["ENCODER"]);    

string found_value = "";

const char quote = '\u0022';

string encoder = "[" + quote + "format" + quote + "][" + quote + "tags" + quote + "][" + quote + "ENCODER" + quote + "]";

// Just as a test
encoder = encoder.Replace("\u005c\u0022", "\u0022");   

// This Fails   
found_value = (dict[encoder]); 

It throws an exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll but was not handled in user code Additional information: The given key was not present in the dictionary.

So I'm sure it's the way I'm passing the encoder string. Probably something really simple but I've spent hours trying various things and become blind to it now.

Thanks in advance

1 answer

  • answered 2018-01-11 19:44 Adam Brown

    Basically, C# isn't a scripting language, but is a compiled language. This means that there is no equivalent of a javascript eval() function, and strings don't perform the same as the equivalent code string. So the second lookup, you're trying to do this:

    dict["[\"format\"][\"tags\"][\"eval\"]")

    And it is rightly complaining that your first dictionary there doesn't have a key of the name

    "[\"format\"][\"tags\"][\"eval\"]"
    

    Why are you trying to do this in the second way, when the first one works?