Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net SimpleJson: Deserialize JSON to dynamic object

Tags:

json

c#

.net

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?

like image 555
Johnny Oshika Avatar asked Oct 21 '11 18:10

Johnny Oshika


3 Answers

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
like image 187
Johnny Oshika Avatar answered Nov 12 '22 00:11

Johnny Oshika


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.

like image 33
dlev Avatar answered Nov 12 '22 01:11

dlev


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

like image 34
BLUEPIXY Avatar answered Nov 12 '22 01:11

BLUEPIXY