I'm using the SimpleJson library from here: http://simplejson.codeplex.com/
I'd like to deserialize a JSON string to an dynamic object like this:
dynamic json = SimpleJson.SimpleJson.DeserializeObject("{\"foo\":\"bar\"}");
var test = json.foo;
The deserialization part works properly, but calling json.foo throws a RuntimeBinderException with the error message 'SimpleJson.JsonObject' does not contain a definition for 'foo'
.
How can I deserialize a JSON string using SimpleJson and access the dynamic properties using the json.foo syntax?
Well, it's just a matter of reading the source code for SimpleJson. :-) A line needs to be uncommented to support the dynamic syntax that I'm looking for. Not sure why this isn't enabled by default.
From the source code:
// NOTE: uncomment the following line to enable dynamic support.
//#define SIMPLE_JSON_DYNAMIC
Looking at the samples, JsonObject
properties are accessed like a dictionary. So instead of json.foo
, you would need json["foo"]
.
You are actually worse off using dynamic
here, since there's nothing dynamic about it: the method returns JsonObject
, which simply doesn't have a foo
member. If you hadn't used dynamic
, you could have gotten that error message at compile time.
If you have a look at the link L.B. provided, it shows how to implement this dynamic functionality yourself.
>csc /t:library /d:SIMPLE_JSON_DYNAMIC SimpleJson.cs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With