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:

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.