public void AreNotEqual(string a, string b) { var aSchema = JsonSchema.FromText(a); var bSchema = JsonSchema.FromText(b); Assert.AreNotEqual(aSchema, bSchema); }
/// <summary> /// Validate the string contents represent a valid SPDX JSON document. /// </summary> /// <param name="jsonString"></param> /// <returns></returns> public static ValidationResult Validate(string jsonString) { var assembly = typeof(JsonValidator).GetTypeInfo().Assembly; using (var schemaStream = assembly.GetManifestResourceStream($"CycloneDX.Spdx.Schemas.spdx-2.2.schema.json")) using (var schemaStreamReader = new StreamReader(schemaStream)) { var jsonSchema = JsonSchema.FromText(schemaStreamReader.ReadToEnd()); try { var jsonDocument = JsonDocument.Parse(jsonString); return(Validate(jsonSchema, jsonDocument)); } catch (JsonException exc) { return(new ValidationResult { Valid = false, Messages = new List <string> { exc.Message } }); } } }
/// <summary> /// Validate the string contents represent a valid CycloneDX JSON document. /// </summary> /// <param name="jsonString"></param> /// <param name="specificationVersion"></param> /// <returns></returns> public static ValidationResult Validate(string jsonString, SpecificationVersion specificationVersion) { if (specificationVersion < SpecificationVersion.v1_2) { throw new Exceptions.UnsupportedFormatSpecificationVersionException($"JSON format is not supported by schema version {specificationVersion}"); } var schemaVersionString = SchemaVersionResourceFilenameString(specificationVersion); var assembly = typeof(Validator).GetTypeInfo().Assembly; using (var schemaStream = assembly.GetManifestResourceStream($"CycloneDX.Core.Schemas.bom-{schemaVersionString}.schema.json")) using (var schemaStreamReader = new StreamReader(schemaStream)) { var jsonSchema = JsonSchema.FromText(schemaStreamReader.ReadToEnd()); try { var jsonDocument = JsonDocument.Parse(jsonString); return(Validate(jsonSchema, jsonDocument, schemaVersionString)); } catch (JsonException exc) { return(new ValidationResult { Valid = false, Messages = new List <string> { exc.Message } }); } } }
public void RoundTrip(string text) { var schema = JsonSchema.FromText(text); var returnToText = JsonSerializer.Serialize(schema); Assert.AreEqual(text, returnToText); }
public void FromText() { var schema = JsonSchema.FromText("{\"$id\":\"http://my.schema/test1\",\"minimum\":5}"); using var json = JsonDocument.Parse("10"); var results = schema.Validate(json.RootElement); Assert.True(results.IsValid); }
public void Issue19_Draft4ShouldInvalidateAsUnrecognizedSchema_NoOption() { var schema = JsonSchema.FromText("{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"type\":\"string\"}"); var instance = JsonDocument.Parse("\"some string\""); var result = schema.Validate(instance.RootElement, new ValidationOptions { OutputFormat = OutputFormat.Detailed }); result.AssertInvalid(); }
public ValidationResult Validate(string schema) { try { var x = JsonSchema.FromText(schema); return(ValidationResult.Success); } catch (System.Exception e) { return(new ValidationResult(e.Message)); } }
/// <summary> /// Converts a Json Schema string to a <see cref="ModelMetadata"/> /// </summary> /// <param name="modelName">The name of the model.</param> /// <param name="jsonSchema">The Json Schema to be converted</param> /// <returns>An flattened representation of the Json Schema in the form of <see cref="ModelMetadata"/></returns> public ModelMetadata Convert(string modelName, string jsonSchema) { ModelName = modelName; _modelMetadata = new ModelMetadata(); _schema = JsonSchema.FromText(jsonSchema); var schemaUri = _schema.GetKeyword <IdKeyword>().Id; _schemaXsdMetadata = _schemaAnalyzer.AnalyzeSchema(_schema, schemaUri); ProcessSchema(_schema); return(_modelMetadata); }
public void Constructor_TemplateExists_ShouldSetCorrectValues() { // Arrange JsonSchemaKeywords.RegisterXsdKeywords(); var expectedId = "https://dev.altinn.studio/org/repository/app/model/model.schema.json"; // Act var actualJsonTemplate = new GeneralJsonTemplate(new Uri(expectedId), "model"); // Assert JsonSchema jsonSchema = JsonSchema.FromText(actualJsonTemplate.GetJsonString()); var idKeyword = jsonSchema.GetKeyword <IdKeyword>(); idKeyword.Id.Should().Be(expectedId); var messageType = jsonSchema.FollowReference(JsonPointer.Parse("#/$defs/model")).Should().NotBeNull(); }
static Validator() { // I think the global schema registry is not thread safe // well, I'm pretty sure, it's the only thing I can think of that would explain the sporadic test failures // might as well just do it once on initialisation var assembly = typeof(Validator).GetTypeInfo().Assembly; using (var spdxStream = assembly.GetManifestResourceStream("CycloneDX.Core.Schemas.spdx.schema.json")) using (var spdxStreamReader = new StreamReader(spdxStream)) { var spdxSchema = JsonSchema.FromText(spdxStreamReader.ReadToEnd()); SchemaRegistry.Global.Register(new Uri("file://spdx.schema.json"), spdxSchema); } using (var jsfStream = assembly.GetManifestResourceStream("CycloneDX.Core.Schemas.jsf-0.82.schema.json")) using (var jsfStreamReader = new StreamReader(jsfStream)) { var jsfSchema = JsonSchema.FromText(jsfStreamReader.ReadToEnd()); SchemaRegistry.Global.Register(new Uri("file://jsf-0.82.schema.json"), jsfSchema); } }
public void Test() { var schema = JsonSchema.FromText(@"{}"); var instance = JsonDocument.Parse(@"{}").RootElement; var validationOptions = new ValidationOptions { OutputFormat = OutputFormat.Basic }; var results = schema.Validate(instance, validationOptions); var serializerOptions = new JsonSerializerOptions { WriteIndented = true }; Console.WriteLine(JsonSerializer.Serialize(schema, serializerOptions)); Console.WriteLine(); Console.WriteLine(JsonSerializer.Serialize(instance, serializerOptions)); Console.WriteLine(); Console.WriteLine(JsonSerializer.Serialize(results, serializerOptions)); }
public bool IsValid(string data, out string result) { if (!string.IsNullOrWhiteSpace(Schema)) { var doc = JsonDocument.Parse(data); JsonSchema schema = JsonSchema.FromText(Schema); var options = new ValidationOptions { OutputFormat = OutputFormat.Detailed }; var validationResult = schema.Validate(doc.RootElement, options); result = GetValidationResultMessage(validationResult); return(validationResult.IsValid); } else { throw new Exception("Schema not set"); } }
private static async Task RunFull(int iterations) { var schemaText = await File.ReadAllTextAsync("SimplePropsSchema.json"); var instanceText = await File.ReadAllTextAsync("SimplePropsInstance.json"); await Time($"NJsonSchema {iterations} runs", async() => { var schema = await NJsonSchema.JsonSchema.FromJsonAsync(schemaText); return(!schema.Validate(instanceText).Any()); }, iterations); await Time($"json-everything {iterations} runs", async() => { var schema = JsonSchema.FromText(schemaText); var instance = JsonDocument.Parse(instanceText); return(schema.Validate(instance.RootElement).IsValid); }, iterations); }
public void MultiDraftSelfValidation() { var json = @"{ ""$defs"": { ""M"": { ""$id"": ""http://localhost/M"", ""$schema"": ""https://json-schema.org/draft/2020-12/schema"", ""$defs"": { ""MarkConfig"": { ""type"": ""integer"" } } }, ""C"": { ""$id"": ""http://localhost/C"", ""$schema"": ""http://json-schema.org/draft-06/schema#"", ""$defs"": { ""Config"": { ""$ref"": ""http://localhost/M#/$defs/MarkConfig"" } }, ""$ref"": ""http://localhost/C#/$defs/Config"" } }, ""$ref"": ""/C"" }" ; var schema = JsonSchema.FromText(json); var instance = JsonDocument.Parse(json).RootElement; var result = schema.Validate(instance, new ValidationOptions { Log = new TestLog(), OutputFormat = OutputFormat.Detailed, DefaultBaseUri = new Uri("http://localhost/") }); Console.WriteLine(JsonSerializer.Serialize(result, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, WriteIndented = true })); }
public void GlobalRegistryMissesRef() { var options = new ValidationOptions { OutputFormat = OutputFormat.Detailed }; SchemaRegistry.Global.Fetch = uri => { if (uri.AbsoluteUri == "http://my.schema/test2") { return(JsonSchema.FromText("{\"type\": \"string\"}")); } return(null); }; var schema = JsonSchema.FromText("{\"$ref\":\"http://my.schema/test1\"}"); using var json = JsonDocument.Parse("10"); var results = schema.Validate(json.RootElement, options); results.AssertInvalid(); results.SchemaLocation.Segments.Last().Value.Should().Be("$ref"); }
/// <inheritdoc/> public IList <JsonSchemaValidationResult> Validate(byte[] jsonBuffer, TextReader schemaReader) { if (jsonBuffer is null) { throw new ArgumentNullException(nameof(jsonBuffer)); } if (schemaReader is null) { throw new ArgumentNullException(nameof(schemaReader)); } var schema = JsonSchema.FromText(schemaReader.ReadToEnd()); var jsonString = Encoding.UTF8.GetString(jsonBuffer); // Remove BOM characters from the string if present. var jsonStringWithoutBom = jsonString.Trim(new char[] { '\uFEFF', '\u200B' }); // Use "Basic" output as that will only generate // two levels of validation results (Root and one level down) // see the API documentation for Json Everything for further details // https://gregsdennis.github.io/json-everything/api/Json.Schema.OutputFormat.html var validationOptions = new ValidationOptions() { OutputFormat = OutputFormat.Basic, }; // Run validation ensuring that trailing commas are supported // as it appears trailing commas have been allowable in the // configuration files for some time. var validationResults = schema.Validate( JsonDocument.Parse( jsonStringWithoutBom, new JsonDocumentOptions() { AllowTrailingCommas = true, } ).RootElement, validationOptions); var jsonSchemaValidationResultCollection = new List <JsonSchemaValidationResult>(); // Copy and flatten validation result to generic json validation result objects // as we don't want to bleed JsonSchema.Net lib objects outside of this class. // Add the top level error message before iterating the nested errors to add to the collection. jsonSchemaValidationResultCollection.Add( new JsonSchemaValidationResult( validationResults.IsValid, validationResults.Message, validationResults.SchemaLocation.ToString(), validationResults.InstanceLocation.ToString())); // Iterate the nested errors and push them into the error collection jsonSchemaValidationResultCollection.AddRange( validationResults.NestedResults.Select(nr => new JsonSchemaValidationResult( nr.IsValid, nr.Message, nr.SchemaLocation.ToString(), nr.InstanceLocation.ToString()) )); return(jsonSchemaValidationResultCollection); }
public void Issue18_SomethingNotValidatingRight() { var instance = JsonDocument.Parse(@"{ ""prop1"": { ""name"": ""a"", ""version"": 1 }, ""prop2"": {}, ""prop4"": ""a"", ""prop5"": {}, ""prop6"": { ""firstId"": ""428de96d-d5b2-4d12-8e88-37827099dd02"", ""secondId"": ""428de96d-d5b2-4d12-8e88-37827099dd02"", ""version"": ""test-version"", ""thirdId"": ""428de96d-d5b2-4d12-8e88-37827099dd02"", ""type"": ""test"", ""name"": ""testApp"", ""receiptTimestamp"": ""2019-02-05T12:36:31.2812022Z"", ""timestamp"": ""2012-04-21T12:36:31.2812022Z"", ""extra_key"": ""extra_val"" }, ""prop3"": { ""prop5"": {}, ""metadata"": {}, ""deleteAfter"": 3, ""allowExport"": true } }"); var schema = JsonSchema.FromText(@"{ ""$schema"": ""http://json-schema.org/draft-07/schema#"", ""type"": ""object"", ""required"": [""prop1"", ""prop2"", ""prop3"", ""prop4"", ""prop5"", ""prop6""], ""properties"": { ""prop1"": { ""type"": ""object"", ""required"": [""name"", ""version""], ""additionalProperties"": false, ""properties"": { ""name"": { ""type"": ""string"", ""pattern"": ""^[-_]?([a-zA-Z][-_]?)+$"" }, ""version"": { ""type"": ""integer"", ""minimum"": 1 } } }, ""prop2"": { ""$ref"": ""http://json-schema.org/draft-07/schema#"" }, ""prop3"": { ""type"": ""object"", ""required"": [ ""prop5"", ""metadata"" ], ""additionalProperties"": false, ""properties"": { ""prop5"": { ""type"": ""object"" }, ""metadata"": { ""type"": ""object"" }, ""deleteAfter"": { ""type"": ""integer"" }, ""allowExport"": { ""type"": ""boolean"" } } }, ""prop4"": { ""type"": ""string"", ""pattern"": ""^[-_]?([a-zA-Z][-_]?)+$"" }, ""prop5"": { ""type"": ""object"" }, ""prop6"": { ""type"": ""object"", ""required"": [ ""firstId"", ""secondId"", ""version"", ""thirdId"", ""type"", ""name"", ""receiptTimestamp"", ""timestamp"" ], ""properties"": { ""firstId"": { ""type"": ""string"", ""pattern"": ""[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"" }, ""secondId"": { ""type"": ""string"", ""pattern"": ""[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"" }, ""type"": { ""type"": ""string"", ""enum"": [""test"", ""lab"", ""stage"", ""prod""] }, ""thirdId"": { ""type"": ""string"", ""pattern"": ""[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"" }, ""version"": { ""type"": ""string"", ""minLength"": 1 }, ""name"": { ""type"": ""string"", ""minLength"": 1 }, ""receiptTimestamp"": { ""type"": ""string"", ""format"": ""date-time"" }, ""timestamp"": { ""type"": ""string"", ""format"": ""date-time"" } }, ""additionalProperties"": { ""type"": ""string"" } } }, ""additionalProperties"": false }"); var result = schema.Validate(instance.RootElement, new ValidationOptions { OutputFormat = OutputFormat.Detailed }); result.AssertValid(); }