Path: redb-route/redb.Route/Validation/JsonSchemaValidator.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Validation/JsonSchemaValidator.cs
----
using System.Text.Json;
using Json.Schema;
using redb.Route.Abstractions;
namespace redb.Route.Validation;
///
/// Validates JSON message bodies against a JSON Schema (draft 2020-12 and earlier).
/// Uses the JsonSchema.Net library internally.
///
/// The validator extracts the body as a string and parses it, or takes a
/// / body directly.
///
///
public sealed class JsonSchemaValidator : IMessageValidator
{
private readonly JsonSchema _schema;
private readonly EvaluationOptions _options;
/// Creates a validator from a pre-parsed .
/// The JSON Schema to validate against.
public JsonSchemaValidator(JsonSchema schema)
{
_schema = schema ?? throw new ArgumentNullException(nameof(schema));
_options = new EvaluationOptions
{
OutputFormat = OutputFormat.List,
RequireFormatValidation = true
};
}
/// Creates a validator from a JSON Schema string.
/// JSON Schema as a string.
public JsonSchemaValidator(string schemaJson)
: this(JsonSchema.FromText(schemaJson ?? throw new ArgumentNullException(nameof(schemaJson))))
{
}
///
public ValidationResult Validate(IExchange exchange)
{
ArgumentNullException.ThrowIfNull(exchange, nameof(exchange));
JsonDocument doc;
var body = exchange.In.Body;
if (body is null)
return ValidationResult.Failure("Message body is null");
if (body is JsonDocument jdoc)
{
doc = jdoc;
}
else if (body is JsonElement jel)
{
// Wrap JsonElement into JsonDocument via serialization round-trip
doc = JsonDocument.Parse(jel.GetRawText());
}
else if (body is string str)
{
try
{
doc = JsonDocument.Parse(str);
}
catch (JsonException ex)
{
return ValidationResult.Failure($"Invalid JSON: {ex.Message}");
}
}
else
{
// Serialize POCO to JSON first
try
{
var json = JsonSerializer.Serialize(body, body.GetType());
doc = JsonDocument.Parse(json);
}
catch (Exception ex)
{
return ValidationResult.Failure($"Cannot serialize body to JSON: {ex.Message}");
}
}
var result = _schema.Evaluate(doc, _options);
if (result.IsValid)
return ValidationResult.Success();
var errors = new List();
if (result.Details != null)
{
foreach (var detail in result.Details)
{
if (detail.HasErrors && detail.Errors != null)
{
foreach (var error in detail.Errors)
{
errors.Add($"{detail.InstanceLocation}: {error.Value}");
}
}
}
}
if (errors.Count == 0)
errors.Add("JSON Schema validation failed");
return ValidationResult.Failure(errors);
}
}