Pular para o conteúdo principal
Versão: main (dev) 🚧

ITLab.Template.DevPack.JsonConverters

Provides custom System.Text.Json converters for domain-specific types and serialization edge cases.

Componentes​

TipoNomeResponsabilidade
ClassIgnoreOffsetJsonConverterStrips the UTC offset from ISO 8601 DateTimeOffset values during deserialization
ClassOneOfJsonConverterHandles serialization and deserialization of OneOf<T0, T1, ...> discriminated unions
ClassRoundedDoubleJsonConverterReads and writes RoundedDouble struct values with consistent decimal precision
ClassStrictEnumJsonConverter<TEnum>JsonStringEnumConverter<TEnum> with the integer form disabled: rejects 2, "2" and undefined values, and throws on writing one — while keeping the schema classification, so the published enum: [...] survives

Como usar​

// Register converters globally in the JSON options.
services.ConfigureHttpJsonOptions(opts =>
{
opts.SerializerOptions.Converters.Add(new IgnoreOffsetJsonConverter());
opts.SerializerOptions.Converters.Add(new RoundedDoubleJsonConverter());
});

StrictEnumJsonConverter<TEnum> is applied by attribute on the enum type, so every contract that carries the enum inherits the rule — including EDocumentKind? and EDocumentKind as a dictionary key:

[JsonConverter(typeof(StrictEnumJsonConverter<EDocumentKind>))]
public enum EDocumentKind
{
Cnpj = 1,
Cpf = 2
}

Query-string and route binding does not go through System.Text.Json and therefore ignores the attribute. Bind on the same matcher the converter delegates to — EnumHelper.TryParseStrict<TEnum> — so a value has the same outcome in the body and in the query:

public readonly record struct DocumentKindParameter(EDocumentKind? Value, string? RejectedText)
: IParsable<DocumentKindParameter>
{
// Never fails the binding: returning false would make the framework answer 400 with an empty
// body and no errorCode. Carry the rejected text and let the handler refuse it with the
// error catalog.
public static bool TryParse(string? s, IFormatProvider? provider, out DocumentKindParameter result)
{
result = EnumHelper.TryParseStrict<EDocumentKind>(s, out var value)
? new DocumentKindParameter(value, null)
: new DocumentKindParameter(null, s);

return true;
}

public static DocumentKindParameter Parse(string s, IFormatProvider? provider)
{
TryParse(s, provider, out var result);
return result;
}
}

O que não fazer​

  • Do not use IgnoreOffsetJsonConverter when the consumer requires timezone-aware datetimes.
  • Do not register duplicate converter instances for the same type.
  • Do not hand-write a JsonConverter<TEnum> for an enum that appears in a published OpenAPI contract, and do not rewrite StrictEnumJsonConverter<TEnum> as one. Microsoft.AspNetCore.OpenApi classifies a type as a string enum by recognising the built-in converter through System.Text.Json's schema exporter. A custom converter is not recognised and the exporter emits an unconstrained schema: the component degrades to {}, losing enum, type and any description built from them, and an array of that enum loses its items entirely — a client generator then produces any[]. Nothing in the build reports it. Measured on .NET 10: 20 enum components emptied and 2 $ref lost across one real contract. A schema transformer can repair the component but never the array, because the items was never emitted in the first place.
  • Do not use plain JsonStringEnumConverter<TEnum> on a contract enum either — it accepts 2, "2" and 99, so an undefined value reaches the domain (ArgumentOutOfRangeException → 500) and re-serializes as a number.
  • Do not reimplement the matching rule inside a query/route binder. Call EnumHelper.TryParseStrict<TEnum>.
  • Do not expect a JsonNamingPolicy. The declared member names are the contract.

Resíduo conhecido: vírgula​

"Cnpj,Cpf" is still accepted and composes a value by OR-ing the members. JsonStringEnumConverter<TEnum> exposes no switch for it, and closing it requires a hand-written converter — which costs the schema. Measured on .NET 10: the exporter classifies by the concrete converter type, so even a decorator that wraps the built-in converter and only pre-checks the comma loses the classification (EnumConverter<T> → {"enum":[...]}; decorator → true, and the array items goes with it). JsonStringEnumConverter<TEnum>.CreateConverter is sealed, so inheritance is closed too. There is no supported way to have both.

A validator alone does not close it, and Enum.IsDefined is the trap. With contiguous members the composition lands on a defined member, so the guard passes. Two cases from the first product to audit for it:

EnumInputMeansConsequence
{ Nuclea = 1, B3 = 2, Cerc = 3 }"Nuclea,B3"Cercenvelope routed to a registrar the caller never named — a billed call, answered 202
{ Incluir = 1, Alterar = 2, Excluir = 3 }"Incluir,Alterar"Excluira request to add a payment instrument performs a delete

1, 2, 3 is the default numbering, which makes this the common case. It also needs no bad faith to trigger: "Incluir,Alterar" is what someone writes assuming the API takes a list. And after deserialization the composition is indistinguishable — "Nuclea,B3" and "Cerc" are the same 3 — so no guard downstream can tell them apart.

The mitigation that works is the numbering. Give the members disjoint values — 1, 2, 4, 8, … — so every composition lands on a value the type does not define:

public enum EscrituradoraContract { Nuclea = 1, B3 = 2, Cerc = 4 }

Must(Enum.IsDefined) in a validator is then what turns those undefined compositions into a refusal. It is the second half, not an alternative: on contiguous members it refuses nothing.

Scope the audit to the enums the caller sends. In a 25-enum contract, 19 had a colliding composition but only 6 were inbound, and 4 of those were exposed; for the rest the value is the server's own. Renumbering costs nothing on the wire — the schema publishes names — but check first that the values are free: no cast to or from int, not persisted as a column, not matched by value in a mapper. Record the reason in a <remarks> on the type, or the next person restores 1, 2, 3.

Extensão pelo produto​

  • Products can add converters for product-specific value objects by following the JsonConverter<T> pattern used in this namespace.
  • A custom JsonConverter<T> that may be used on a dictionary key must override ReadAsPropertyName/WriteAsPropertyName. The base implementations throw at runtime and the build does not catch it. StrictEnumJsonConverter<TEnum> inherits working ones from the built-in converter.
  • When adding a converter for a type that appears in a published contract, assert its JsonSerializerOptions.GetJsonSchemaAsNode(type) in a test. It is the only place the schema damage shows up before a consumer's contract is already broken.