Generic Base Class with JsonConverter for Contentstack Block Model Classes

This is one of those cases where I left a bunch of leather and nails on my desk before bed and woke up to find crumbs on the keyboard and a working prototype (cobbled together, no doubt) that I can barely read, let alone understand, but seems to work. My fingers thank C# generics and reflection for allowing me to avoid individual JsonConverters.

I intend to provide an example in another post. Basically:

  • All Block Model classes derive from the implementation of the base class (I think – I might have to update this), which must be in the same assembly as this base class (for performance – I also have code that iterates all assemblies to find implementations).
  • To model Modular Blocks, Entry Model classes contain properties of type List<TBlockModelBaseClass>, where TBlockModelBaseClass is the base class for the Block Model classes that model the types of blocks that can appear in that Field.
  • Before deserialization from JSON to an Entry Model, a single piece of code iterates the implementations of (the implementation of, I think) the base and adds the required JsonConverter to the SerializationSettings.
  • The Converters read a value from the block of JSON to identify its type, and then instantiate the type that exposes that value as an enum before serialization continues.

I left in the that the eventual base class derives from something else called Component, which exposes a Field that the developer or CMS user can use to specify a partial view to invoke, logically to receive the Block Model.

https://pastebin.com/tiVY9Dpz

Here is the logic to add the JsonConverers.

https://pastebin.com/bQAnmKa0

Note that this could also be a way to store the raw JSON in the Block Model as described for Entry Models at https://deliverystack.net/2020/07/23/expose-entry-json-from-entry-model/.

P.S. I see that I left a different autoloading JsonConverter technique in the code, using attributes. You can see the logic for adding them to SerializationSettings in the code above.

AutoLoadJsonConverter (should be named AutoLoadJsonConverterAttribute I think): https://pastebin.com/RJFNGY3N

Base class for AutoLoadJsonConverterAttribute: https://pastebin.com/3FKSPCPP

4 thoughts on “Generic Base Class with JsonConverter for Contentstack Block Model Classes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: