UnitsNet – Tiny JSON Serializer

UnitsNet is a popular framework for unit of measure conversion in applications. One nice aspect of the framework is that it handles unit serialization to JSON. The documentation gives an example of a unit of measure that’s been serialized to JSON.

{ "weight": { "unit": "MassUnit.Kilogram", "value": 90.0 } }

Thus, an array of values would be represented as the following.

{ "weights": [ { "unit": "MassUnit.Kilogram", "value": 90.0 }, { "unit": "MassUnit.Kilogram", "value": 90.1 }, { "unit": "MassUnit.Kilogram", "value": 90.2 } ] }

For most applications this will work well. However, in scenarios where you need to send thousands of unit values in a JSON response, the default serialization is verbose. Looking around the for a solution I came across the idea of serializing the quantity and unit of measure as a string. Here is an example of what that’d look like for the same scenarios shown above.

{ "weight": "90.0|kg" }

Here is the array of values simplified in representation.

{ "weights": ["90.0|kg","90.1|kg","90.2|kg"] }

It is easy to see the savings in size of JSON going over the wire with this simplified representation. The example project is available on Github. The code is relatively simple, but I’ll outline a few things that may not be so obvious here…

• The serialization uses the abbreviation for a unit. If a unit has two abbreviations that are the same (think dictionary key violation), then this serializer will fail. • Swagger UI will show the full model for a UnitsNet unit unless you override this with a custom OpenApiSchema. • Swagger OpenApiSchema’s need to be provided per unit type. • This code does not handle collections of mixed unit types.

If you're using UnitsNet and need a lighter serializer pull the project and have a look.