Class ValidatingJsonConverter<TValue, TPrimitive>
- Namespace
- Trellis.Asp.Validation
- Assembly
- Trellis.Asp.dll
A JSON converter for value objects that implement IScalarValue<TSelf, TPrimitive>. This converter collects validation errors instead of throwing exceptions, enabling comprehensive validation error responses.
public sealed class ValidatingJsonConverter<TValue, TPrimitive> : ScalarValueJsonConverterBase<TValue?, TValue, TPrimitive> where TValue : class, IScalarValue<TValue, TPrimitive> where TPrimitive : IComparable
Type Parameters
TValueThe type of the value object to convert.
TPrimitiveThe underlying primitive type.
- Inheritance
-
JsonConverter<TValue>ScalarValueJsonConverterBase<TValue, TValue, TPrimitive>ValidatingJsonConverter<TValue, TPrimitive>
- Inherited Members
- Extension Methods
Remarks
This converter enables the pattern where DTOs can contain value objects directly, and all validation errors are collected during deserialization rather than failing on the first invalid value.
When a value fails validation:
- The error is added to ValidationErrorsContext
- A default value (null) is returned
- Deserialization continues to collect additional errors
After deserialization, use ScalarValueValidationFilter to check for errors and return appropriate 400 Bad Request responses.
Methods
OnNullToken(string)
Returns the result when a JSON null token is read.
protected override TValue? OnNullToken(string fieldName)
Parameters
fieldNamestringThe resolved field name for error reporting.
Returns
- TValue
OnValidationFailure()
Returns the result when validation fails.
protected override TValue? OnValidationFailure()
Returns
- TValue
WrapSuccess(TValue)
Wraps a successfully validated value object into the result type.
protected override TValue? WrapSuccess(TValue value)
Parameters
valueTValue
Returns
- TValue
Write(Utf8JsonWriter, 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, TValue? value, JsonSerializerOptions options)
Parameters
writerUtf8JsonWriterThe writer to write to.
valueTValueThe value to convert to JSON.
optionsJsonSerializerOptionsAn object that specifies serialization options to use.