HyperDev.Text.Json.Schema
1.2.0
dotnet add package HyperDev.Text.Json.Schema --version 1.2.0
NuGet\Install-Package HyperDev.Text.Json.Schema -Version 1.2.0
<PackageReference Include="HyperDev.Text.Json.Schema" Version="1.2.0" />
<PackageVersion Include="HyperDev.Text.Json.Schema" Version="1.2.0" />
<PackageReference Include="HyperDev.Text.Json.Schema" />
paket add HyperDev.Text.Json.Schema --version 1.2.0
#r "nuget: HyperDev.Text.Json.Schema, 1.2.0"
#:package HyperDev.Text.Json.Schema@1.2.0
#addin nuget:?package=HyperDev.Text.Json.Schema&version=1.2.0
#tool nuget:?package=HyperDev.Text.Json.Schema&version=1.2.0
HyperDev.Text.Json.Schema
A JSON Schema Draft 7 validator and object model for Newtonsoft.Json (JToken).
- Fully conformant: passes all 927 required tests of the official
JSON-Schema-Test-Suite (draft7) and the optional ones,
formatincluded, and is checked against about 900 real-world schemas from SchemaStore. - One dependency, Newtonsoft.Json (MIT). No license limits on the number of validations.
- A mutable object model (
JsonSchema) to read, navigate, build and edit schemas, and an immutable, thread-safe compiled validator (JsonSchemaValidator) for hot paths. - Alternative signatures (
IsValidwith anoutlist of errors, aValidatethat throws) for code written in that style. - Targets .NET 8 and .NET 10.
Validate
using HyperDev.Text.Json.Schema;
var validator = JsonSchemaValidator.FromText(schemaJson); // or FromFile / FromToken
ValidationResult result = validator.Validate(JsonParsing.Parse(json));
if (!result.IsValid)
foreach (var error in result.Errors)
Console.WriteLine($"{error.InstancePath}: {error.Message} ({error.Keyword})");
bool ok = validator.IsValid(token); // fast: stops at the first error
Every $ref is resolved when the schema is compiled, so a broken reference shows up immediately as a
JsonSchemaException. Compile a schema once and share the JsonSchemaValidator: it is immutable and thread-safe.
Extension methods work with both JsonSchema and JsonSchemaValidator:
ValidationResult r = token.Validate(schema); // returns the result, does not throw
ValidationResult f = token.Validate(schema, new ValidationSettings { StopOnFirstError = true });
bool valid = token.IsValid(schema);
token.EnsureValid(schema); // throws JsonSchemaValidationException
ValidationResult j = json.ValidateJson(schema); // from JSON text
Parse the values to validate with
JsonParsing.Parse(json): unlikeJToken.Parse, it keeps date-like strings as strings, so the original text is validated.
The JsonSchema model
var schema = JsonSchema.Parse(text); // or FromFile / FromToken
schema.Properties["name"].MaxLength = 50; // edit
var built = new JsonSchema
{
Type = SchemaType.Object,
Required = { "name" },
Properties = { ["name"] = new JsonSchema { Type = SchemaType.String, MaxLength = 50 } },
AdditionalProperties = JsonSchema.False,
};
string json = built.ToString(); // or ToJToken()
bool ok = built.IsValid(token); // compiled on demand, cached until the next change
JsonSchemaValidator compiled = built.Compile(); // immutable snapshot
- One property per Draft 7 keyword, named after the keyword:
MinLength,MaxItems,Definitions,Ref($ref),Comment($comment)… For a single value,nullmeans the keyword is absent. - Collections (
Properties,Required,AllOf,Enum, …) always exist: they are created empty when first used, cannot be replaced (clear them to remove the keyword), and are written only when they are not empty. - Numbers (
Minimum,Maximum,ExclusiveMinimum,ExclusiveMaximum,MultipleOf) areJToken, so no precision is lost: read them with a cast, e.g.(decimal?)schema.Minimum. - Boolean schemas:
BooleanValue, with the constantsJsonSchema.TrueandJsonSchema.False. items:Items(one schema) orItemsArray(tuple).dependencies:PropertyDependenciesorSchemaDependencies.- Extensions: keywords that are not Draft 7 (e.g.
x-sensitive) are kept inExtensionData. - Tree:
Parent,Root,Pointer(JSON Pointer from the root).ResolveRef()returns the schema a$refpoints to (local,$id, or external documents),ResolveRefChain()follows chains. - Subschemas:
schema.Properties["x"].IsValid(token)validates from a subschema, resolving$refagainst the whole document. ToJToken()writes the keywords in a fixed order and the names intypesorted; the content is unchanged.
Serialization with Newtonsoft.Json
JsonSchema carries a converter (JsonSchemaConverter), so Newtonsoft.Json writes and reads it as a JSON Schema
document, alone or inside other objects, with any settings:
string json = JsonConvert.SerializeObject(new { Name = "customer", Input = schema }); // "Input": { "type": "object", ... }
JToken token = JToken.FromObject(schema); // same as ToJToken()
JsonSchema read = JsonConvert.DeserializeObject<JsonSchema>(json); // same as FromToken()
Reading keeps the text of the document: date-like strings stay strings even with Newtonsoft's default settings. An
invalid schema is a JsonSerializationException with its path. Options and BaseUri are not written.
Options
var options = new JsonSchemaOptions
{
TemporalFormats = TemporalFormatProfile.Rfc3339, // strict Draft 7 date-time / time
StopOnFirstError = true,
};
options.CustomFormats["tax-code"] = value => value.Length == 16;
options.Documents[new Uri("https://example.com/address.json")] = JsonParsing.Parse(addressSchema);
var validator = JsonSchemaValidator.FromText(schemaJson, options);
| Option | Default | Meaning |
|---|---|---|
ValidateFormat |
true |
format is an assertion. Unknown formats are always accepted. |
TemporalFormats |
Iso8601 |
date-time and time accept the ISO 8601 extended format, so a value without an offset is a local time, and duration is checked. Rfc3339 is the strict Draft 7 rule, which requires the offset. |
CustomFormats |
— | Your own format checks; they override the built-in ones. |
ValidateContent |
false |
Enforce contentEncoding: base64 and contentMediaType: application/json. |
StopOnFirstError |
false |
Report only the first error (faster). Also per call with ValidationSettings. |
Documents / DocumentResolver |
— | External schemas referenced by $ref. No network access by default; the draft-07 meta-schema is always available. |
UnknownSchemaVersion |
Throw |
A root $schema other than draft-07 / draft-06 is rejected. TreatAsDraft7 accepts it and ignores the non-Draft 7 keywords. |
RegexTimeout, MaxDepth |
2 s, 1000 | Protection against slow patterns and infinite $ref recursion. |
Alternative signatures
The HyperDev.Text.Json.Schema.Compatibility namespace adds an IsValid that returns the errors in an out list and a
Validate that throws, for code written in that style:
using HyperDev.Text.Json.Schema;
using HyperDev.Text.Json.Schema.Compatibility;
bool ok = token.IsValid(schema, out IList<string> errors); // messages of the errors
bool ok2 = token.IsValid(schema, out IList<ValidationError> details);
token.Validate(schema); // throws JsonSchemaValidationException
With the namespace imported, token.Validate(schema) throws; without it, it returns a ValidationResult. Custom keyword
validators are not supported: use CustomFormats for custom checks.
Scope and limits
- Draft 7 (and draft-06 schemas). Drafts 2019-09 and 2020-12 are rejected unless you opt in with
TreatAsDraft7. - Newtonsoft.Json only: System.Text.Json is not supported.
idn-hostname/idn-emailapproximate the IDNA2008 / UTS 46 tables with Unicode categories; all the suite cases pass.- Regular expressions are translated from ECMA-262 to .NET; exotic constructs such as character classes with non-BMP code points are not supported.
License
MIT © Ivan Senatore, Wemake Informatica srl
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Newtonsoft.Json (>= 13.0.3)
-
net8.0
- Newtonsoft.Json (>= 13.0.3)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on HyperDev.Text.Json.Schema:
| Package | Downloads |
|---|---|
|
HyperDev.Text.Json.Transform
HyperDev Fatum Framework: JsonTransform and the Newtonsoft.Json.Schema helpers (inference, samples, validation) |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.2.0 | 53 | 11/11/2026 |