Creating JSON in C#

I recently had the task to send some JSON to a REST API. After deciding to use Newtonsoft.JSON I wondered how to nicely create the JSON structure I needed.

Of course it would be possible to create a class, instantiate it and then serialize it to JSON, but due to the fact that I needed many different items that would have been quite a set of classes…

The dynamic solution

The solution was to use dynamic objects – a feature that I’ve ignored for too long, as I’ve noticed. At compile time, an element that is typed as dynamic is assumed to support any operation. So you can safely write something like this:

Note that apart from List<object> there’s no other class involved. This provides you with an object that magically has all the properties. You can even pass it around to other methods that expect a dynamic parameter:

And of course you can also serialize it to JSON – all you need to do is make your object so it fits the required JSON format.

Schreiben Sie einen Kommentar

Ihre E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.