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
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="HyperDev.Text.Json.Schema" Version="1.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="HyperDev.Text.Json.Schema" Version="1.2.0" />
                    
Directory.Packages.props
<PackageReference Include="HyperDev.Text.Json.Schema" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add HyperDev.Text.Json.Schema --version 1.2.0
                    
#r "nuget: HyperDev.Text.Json.Schema, 1.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package HyperDev.Text.Json.Schema@1.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=HyperDev.Text.Json.Schema&version=1.2.0
                    
Install as a Cake Addin
#tool nuget:?package=HyperDev.Text.Json.Schema&version=1.2.0
                    
Install as a Cake Tool

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, format included, 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 (IsValid with an out list of errors, a Validate that 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): unlike JToken.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, null means 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) are JToken, so no precision is lost: read them with a cast, e.g. (decimal?)schema.Minimum.
  • Boolean schemas: BooleanValue, with the constants JsonSchema.True and JsonSchema.False.
  • items: Items (one schema) or ItemsArray (tuple). dependencies: PropertyDependencies or SchemaDependencies.
  • Extensions: keywords that are not Draft 7 (e.g. x-sensitive) are kept in ExtensionData.
  • Tree: Parent, Root, Pointer (JSON Pointer from the root). ResolveRef() returns the schema a $ref points to (local, $id, or external documents), ResolveRefChain() follows chains.
  • Subschemas: schema.Properties["x"].IsValid(token) validates from a subschema, resolving $ref against the whole document.
  • ToJToken() writes the keywords in a fixed order and the names in type sorted; 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-email approximate 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 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)

HyperDev.Connectors

HyperDev Fatum Framework

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.2.0 176 11/11/2026