Class MaybeScalarValueJsonConverter<TValue, TPrimitive>
- Namespace
- Trellis.Asp.Validation
- Assembly
- Trellis.Asp.dll
A JSON converter for Maybe<T> properties where TValue
implements IScalarValue<TSelf, TPrimitive>.
public sealed class MaybeScalarValueJsonConverter<TValue, TPrimitive> : ScalarValueJsonConverterBase<Maybe<TValue>, TValue, TPrimitive> where TValue : class, IScalarValue<TValue, TPrimitive> where TPrimitive : IComparable
Type Parameters
TValueThe scalar value object type.
TPrimitiveThe underlying primitive type.
- Inheritance
-
JsonConverter<Maybe<TValue>>ScalarValueJsonConverterBase<Maybe<TValue>, TValue, TPrimitive>MaybeScalarValueJsonConverter<TValue, TPrimitive>
- Inherited Members
- Extension Methods
Examples
public record RegisterUserDto
{
public EmailAddress Email { get; init; } = null!; // required
public Maybe<FirstName> FirstName { get; init; } // optional — null = None
}
Remarks
This converter enables DTOs to use Maybe<T> for optional value object properties:
nullJSON value →Maybe.None<TValue>()— no error, value was not provided- Valid JSON value →
Maybe.From(validated)— value provided and valid - Invalid JSON value → validation error collected, continues deserialization
Unlike ValidatingJsonConverter<TValue, TPrimitive>, this converter treats
JSON null as a valid "not provided" signal rather than an error.
Methods
OnNullToken(string)
Returns the result when a JSON null token is read.
protected override Maybe<TValue> OnNullToken(string fieldName)
Parameters
fieldNamestringThe resolved field name for error reporting.
Returns
- Maybe<TValue>
OnValidationFailure()
Returns the result when validation fails.
protected override Maybe<TValue> OnValidationFailure()
Returns
- Maybe<TValue>
WrapSuccess(TValue)
Wraps a successfully validated value object into the result type.
protected override Maybe<TValue> WrapSuccess(TValue value)
Parameters
valueTValue
Returns
- Maybe<TValue>
Write(Utf8JsonWriter, Maybe<TValue>, JsonSerializerOptions)
Writes a specified value as JSON.
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "TPrimitive type parameter is preserved by JSON serialization infrastructure")]
[UnconditionalSuppressMessage("AOT", "IL3050", Justification = "JSON serialization of primitive types is compatible with AOT")]
public override void Write(Utf8JsonWriter writer, Maybe<TValue> value, JsonSerializerOptions options)
Parameters
writerUtf8JsonWriterThe writer to write to.
valueMaybe<TValue>The value to convert to JSON.
optionsJsonSerializerOptionsAn object that specifies serialization options to use.