Skip to content

Serialization

Daniel Gonzalez Garcia edited this page Feb 2, 2024 · 5 revisions

Serialization Considerations

NOTE:

All sorts of custom serialization has been removed from the netstandard library and v7 takes a very different approach to serialization.

Everything below refers only to the v7 .NET library.

Objectives

Serialization (it's customization or even support) is no longer considered a major feature to be provided by the library.
Therefore, all serialization-related code has been removed in v7.

ˋCurrencyˋ instances and their singleton-like shape should not be serialized. Use ˋCurrencyIsoCodeˋ instead.

ˋMoneyˋ is not really meant for general out-of-the-box serialization.
Serializers/Converters has been provided for "popular" third-party libraries (Newtonsoft.Json, MongoDb.Bson) and modern first-parties (System.Text.Json) and other options are provided when no customization is possible.

Code vs. binaries

Third party serialization used to be included as source code in content Nuget packages.

The move of stop supporting content folders, replacing it with the different contentFiles was, in my opinion, a mistake, defeating the purpose of such kind of packages (packages that add source code files to your project for you to tweak).

I will no longer provide third(first)-party Serialization Nuget pacakges. Instead, code can be copied and pasted (and modified at will) from this Wiki or directly from code in src/NMoneys.Serialization.

Serialization is difficult/impossible to modify

Some serialization frameworks expect the types serialized to support the customizations needed for serializatation and make it very difficult (or impossible) to change the information being sent or read.

That's not a great feature, but there is little that NMoneys can do in that regards, except provide serialization-friendly types (surrogates) that can be easily converted back and forth ˋMoneyˋ and can be used in those DTOs that will be serialized and de-serialized:

  • ˋMonetaryQuantityˋ: a plain-old class with getters and setters.
  • ˋMonetaryRecordˋ: a record.

Serialization can be customized

If you are serializing ˋMoneyˋ with one of the "supported" libraries, just copy and paste the blueprint code in your solution and configure the library to use the serializer/converter.

If your library is not supported you can use one of the surrogate types (ˋMonetaryQuantityˋ or ˋMonetaryRecordˋ) in your DTOs.

System.Text.Json

Newtonsoft.Json

MongoDb.Bson

Persistence

Persistence of ˋMoneyˋ instances to storage (database, files, ...) can be considered like one particular case of serialization.

For that particular case we recommend using either custom Json serialization of one of the supported libraries or the more compact value representation of the ˋMoney.AsQuantity()ˋ method and its ˋMoney.Parse()ˋ counterpart.

EntityFrameworkCore

A couple of custom value converters have been included for EF Core prior to v8.