Monday, November 4, 2019

Creating JSON in C# With Dynamic

I'm excited to share a new (to me) way of creating JSON on-the-fly.  It uses the dynamic type in C#, which I knew about, but hadn't used too much.  Now I see how powerful it really is.

I ran across a problem where I had to build a JSON string to send to a web service as a parameter.  It was short but nested several layers deep.  I also needed it to be highly configurable.  I could build it with a string, or better yet, a StringBuffer.  Or I could build an object, then serialize it to JSON.  The former seems fragile, the later feels like overkill (And, there is nothing worse than trying to decode what another programmer has done with a thousand little classes you have to hunt down.)

Enter the dynamic type.  I knew it was very late-binding, thus avoiding compile-time type checking.  It gets its type at run-time.  So, it infers the type when the program runs and is able to do this:

dynamic nVal = 23.4;
dynamic sVal = "Hello";
Console.WriteLine(nVal.GetType().ToString());   // System.Double
Console.WriteLine(sVal.GetType().ToString());   // System.String

However, a little talked about feature is that it is an object that can be a container too.  And it can contain different types including arrays and objects.  This sets us up to be able to nest JSON very nicely.  Check out this example:

dynamic message = new JObject();
product.to = "UserToken";
product.priority = 5;
product.notification = new JObject();
product.notification.message = "You have a new order.";
product.notification.sound = "default";

Console.WriteLine(message.ToString());

// Output JSON
{
    "to": "UserToken",
    "priority": 5,
    "notification": {
        "message": "You have a new order.",
        "sound": "default"
    }
}

Hopefully, this will help you create simpler JSON data too.

No comments:

Post a Comment