Json.NET Dynamic Extensions

I've been working with RavenDB and Json.NET lately.  RavenDB has some interesting schema-less capabilities using JSON documents.  When interacting with the API, you either get serialized objects or JSON.NET classes.  These are great, but it seemed like mixing in the Dynamic features of C# 4.0 would make things interesting.

So, I've added an extension method to JObject which allows you to get a dynamic instance back.  Here's an example:

   1:      string json = @"{  ""Username"": ""atucker"",  ""Expiration"": new Date(1230422400000),  ""AccessRights"": [    ""Search"",    ""Edit"",    ""Add""  ]}";
   2:   
   3:      JObject jo = JObject.Parse(json);
   4:      dynamic user = jo.AsDynamic();
   5:   
   6:      // Loop through dynamic list of access rights
   7:      foreach (var size in user.AccessRights)
   8:      {
   9:          if (size != null)
  10:              Console.WriteLine(size);
  11:      }
  12:   
  13:      user.FullName = "Adam Tucker";

In the above example, the code is loops through the "AccessRights" dynamic array built off the JSON objects.  The dynamic class actually wraps the JSON objects, so you can read and also update the dynamic object.  What's cool is the dynamic object changes the underlying JSON.  Here is the output of the JSON object after it is modifed:

   1:  {
   2:    "Username": "atucker",
   3:    "Expiration": new Date(
   4:      1230422400000
   5:    ),
   6:    "AccessRights": [
   7:      "Search",
   8:      "Edit",
   9:      "Add"
  10:    ],
  11:    "FullName": "Adam Tucker"
  12:  }

So, how does it work?  The DynamicJsonObject class descends from the DynamicObject class and overrides the GetDynamicMemberNames and TryGetMember methods.  To support arrays, the DynamicJsonArray overrides TryGetIndex and TrySetIndex.  It also implements IEnumerable for good measure.

Now that we have a dynamic object, you can also use my DynamicDuck code to interface it with your statically typed methods.

   1:   // Use Dynamic Duck to use our dynamic JSON via a static interface
   2:   AddUser(DynamicDuck.AsIf<IUser>(user));

Want to try code the code?

 [ Download the source ]

1 Comment

  • In the GetDynamicValue function of the DynamicJsonHelper class you should add the following to the "if" block:

    else if (value is JObject)
    {
    return (value as JObject).AsDynamic();
    }

Comments have been disabled for this content.