6

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?

Yuck
  • 49,664
  • 13
  • 105
  • 135
Johnny Oshika
  • 54,741
  • 40
  • 181
  • 275

3 Answers3

11

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
Johnny Oshika
  • 54,741
  • 40
  • 181
  • 275
  • 2
    That's a fair comment, L.B. I can't delete the question, so hopefully this will serve as a useful artifact for others who install SimpleJson through NuGet and run into the same problem as I did. – Johnny Oshika Oct 24 '11 at 04:55
4

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.

dlev
  • 48,024
  • 5
  • 125
  • 132
1

>csc /t:library /d:SIMPLE_JSON_DYNAMIC SimpleJson.cs

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70