Home C# building a string for JSON using variables
Reply: 1

C# building a string for JSON using variables

HeavyHead
1#
HeavyHead Published in 2018-01-11 19:44:21Z

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

Adam Brown
2#
Adam Brown Reply to 2018-01-11 20:18:58Z

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?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300381 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO