API Reference ResultJsonConverter - ulfbou/Zentient.Results GitHub Wiki
namespace Zentient.Results.SerializationProvides a polymorphic System.Text.Json.Serialization.JsonConverterFactory that serializes and deserializes IResult, IResult<T>, Result, and Result<T> instances with full fidelity, preserving status, messages, errors, and encapsulated values.
| Property | Value |
|---|---|
| ๐ฆ Assembly | Zentient.Results.dll |
| ๐ Visibility | public sealed class |
| โ๏ธ Base Type | System.Text.Json.Serialization.JsonConverterFactory |
| ๐งฑ Implements | Dynamic converter resolution for IResult and derived types |
| ๐ Category | JSON Serialization |
Enables System.Text.Json to:
- Serialize and deserialize
IResultandIResult<T>preserving complete structure. - Customize serialization details based on
JsonSerializerOptions. - Decouple serialization from concrete implementations such as
Result<T>. - Support transport-safe, protocol-agnostic JSON representations.
var options = new JsonSerializerOptions();
options.Converters.Add(new ResultJsonConverter());
string json = JsonSerializer.Serialize(Result<int>.Success(42, "OK"), options);public override bool CanConvert(Type typeToConvert)Determines if the converter supports the specified type.
| Parameter | Type | Description |
|---|---|---|
typeToConvert |
Type |
Type to verify for conversion |
| Returns | Description |
|---|---|
true |
If typeToConvert implements IResult
|
public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)Creates an appropriate JsonConverter instance for the specified result type.
| Parameter | Type | Description |
|---|---|---|
typeToConvert |
Type |
Target type to create converter for |
options |
JsonSerializerOptions |
Serialization options |
| Returns | Description |
|---|---|
JsonConverter |
Converter instance or null if unsupported |
Behavior:
- Returns
ResultGenericJsonConverter<T>for generic types (Result<T>,IResult<T>). - Returns
ResultNonGenericJsonConverterfor non-generic types (Result,IResult). - Returns
nullfor unsupported types.
Supports full serialization/deserialization of Result<T> including fields:
valueisSuccessisFailurestatusmessageserrors-
errorMessage(optional)
Handles Result serialization excluding value property but including all other common fields.
- Avoid multiple registrations of
ResultJsonConverterin differentJsonSerializerOptionsinstances. - Honors camelCase naming via configured
PropertyNamingPolicy. - Gracefully handles partial or unknown fields during deserialization.
{
"value": 100,
"isSuccess": true,
"status": { "code": 0, "description": "Success" },
"messages": ["Completed successfully"]
}| Scenario | Recommendation |
|---|---|
| ASP.NET Core Serialization | Add ResultJsonConverter to JsonOptions.Converters
|
| Polymorphic Deserialization | Use IResult as the contract/interface type |
| Custom Naming Policies | Configure PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|