Object Translator

Class Library
C#
GitHub Repository

What It Is

Code to "translate" a C# object to another object prior to serialization

Status

I used this in the Opti Endpoints POC. Someone else has implemented this in production and told me it worked great.

(However, see my aside below. JSONata might provide a alternate/better way to achieve the same goal.

Details

This code allows you to take a C# object (a POCO) and “translate” it to different object before it’s serialized. So, a complicated C# object can be turned into something much more simple, so that your serialized representation only includes the information you need/want.

You could always do this from C# code, but this system allows you to do this from a text-based specification. You can write and store something like this:

FirstName
Height | append:" inches"
Year: DateOfBirth.Year

Then, in C#:

var newObject = ObjectTranslator.Translate(thatTextAbove, theOriginalObject);

The new object is “constructed” from the old object according to the “rules” in the specification.

When applied to an existing C# object, the example above will create a new (anonymous) object with the following properties:

  1. The value FirstName property will be copied into a property of the same name on the new object

  2. The Height property will be copied into a property of the same name on the new object, with the string “ inches” appended to it (that’s just a Fluid filter BTW, so you could also custom write anything that Fluid supports…)

  3. The value of the Year property on the DateOfBirth property will be extracted into a new (“top-level”) property called Year

There are all sorts of other transformations and option available, including transformations down into collections, etc.

The resulting object can then be serialized. (And serialization is really the only point here – you do this to serialize it, or maybe to inject it into a template context?)