public void Example() { #region Usage // person.json, has a relative external schema reference 'address.json' // -------- // { // 'type': 'object', // 'properties': { // 'name': {'type':'string'}, // 'addresses': { // 'type': 'array', // 'items': {'$ref': 'address.json'} // } // } // } // -------- using (StreamReader file = File.OpenText(@"c:\person.json")) using (JsonTextReader reader = new JsonTextReader(file)) { JSchemaUrlResolver resolver = new JSchemaUrlResolver(); JSchema schema = JSchema.Load(reader, new JSchemaReaderSettings { Resolver = resolver, // where the schema is being loaded from // referenced 'address.json' schema will be loaded from disk at 'c:\address.json' BaseUri = new Uri(@"c:\person.json") }); // validate JSON } #endregion }
public void Example() { #region Usage // resolver will fetch 'http://schema.org/address.json' with a web request as the parent schema is loaded JSchemaUrlResolver resolver = new JSchemaUrlResolver(); JSchema schema = JSchema.Parse(@"{ 'type': 'object', 'properties': { 'name': {'type':'string'}, 'addresses': { 'type': 'array', 'items': {'$ref': 'http://schema.org/address.json'} } } }", resolver); JToken json = JToken.Parse(@"{ 'name': 'James', 'addresses': [ { 'line1': '99 Smithington Street', 'line2': 'Real Town', 'country': 'USA' } ] }"); IList<string> errorMessages; bool isValid = json.IsValid(schema, out errorMessages); #endregion Assert.IsTrue(isValid); }
public void HandleError() { JSchemaUrlResolver resolver = new JSchemaUrlResolver(); resolver.SetDownloader(new MockDownloader()); ExceptionAssert.Throws<JSchemaReaderException>(() => { JSchema.Parse(@"{ 'allOf': [ {'$ref':'http://google.com#'} ] }", resolver); }, "Error when resolving schema reference 'http://google.com/#'. Path 'allOf[0]', line 3, position 9."); }
public async Task openapiv3___specific_version_json_validate_success() { base.SetupEnvironment(); var request = @$ " GET https://{host}/openapi/v3/doc?version=3 HTTP/1.1 Host: {host} Connection: keep-alive User-Agent: UnitTest/1.0 DEV Accept: {applicationJson} "; using var httpContext = new MockHttpContext(this.ServiceProvider, request); var apiContext = await Invoke(httpContext).ConfigureAwait(false); var response = httpContext.Response; base.AssertResponse( apiContext: apiContext, response: response, expectedHttpStatus: 200, expectedContentType: applicationJson, shouldHaveResponse: true, expectedValidationState: ApiValidationState.Succeeded, extendedHeaders: new NameValuePairs <string, string> { }); var data = await base.GetResponseDataString(response).ConfigureAwait(false); //System.Diagnostics.Debug.Write(data); data.Should().NotBeNull(); data.Should().NotBeEmpty(); data.Should().StartWith("{"); data.Should().EndWith("}"); var rawSchema = Encoding.UTF8.GetString(TestResources.openapi_v3); var resolver = new JSchemaUrlResolver(); var schema = JSchema.Parse(rawSchema, resolver); var json = JObject.Parse(data); IList <ValidationError> errors = null; bool valid = json.IsValid(schema, out errors); valid.Should().BeTrue(); }
private static bool Validate(JToken obj, string path, string schemaPath) { JSchemaUrlResolver resolver = new JSchemaUrlResolver(); IList<ValidationError> errors; bool valid = true; using (StreamReader file = File.OpenText(schemaPath)) using (JsonTextReader reader = new JsonTextReader(file)) { JSchema schema = JSchema.Load(reader, new JSchemaReaderSettings { Resolver = resolver, BaseUri = new Uri(schemaPath) }); try { valid = obj.IsValid(schema, out errors); } catch (JSchemaException e) { errors = new List<ValidationError>(); if (e.Message.Contains("free-quota limit")) { valid = true; } else { valid = false; } } if (valid) { return true; } else { foreach (var error in errors) { Console.Error.WriteLine(error.ToString()); } throw new InvalidDataException("Could not validate " + path); } } }
private static JSchema GetSchema(Uri schemaUri) { JSchemaUrlResolver jSchemaResolver = new JSchemaUrlResolver(); Stream stream = null; try { stream = jSchemaResolver.GetSchemaResource(null, new SchemaReference() { BaseUri = schemaUri }); } catch (Exception e) { throw new Stac.Exceptions.InvalidStacSchemaException(string.Format("Error getting schema at Uri '{0}'", schemaUri), e); } var sr = new StreamReader(stream); return(JSchema.Parse(sr.ReadToEnd(), jSchemaResolver)); }
public async Task openapiv3___json_validate_success() { base.SetupEnvironment(); var request = @$ " GET https://{host}/openapi/v3/doc HTTP/1.1 Host: {host} Connection: keep-alive User-Agent: UnitTest/1.0 DEV Accept: {applicationJson}"; using var httpContext = new MockHttpContext(base.serviceProvider, request); var apiContext = await Invoke(httpContext).ConfigureAwait(false); var response = httpContext.Response; response.Should().NotBeNull(); var data = await base.GetResponseDataString(response).ConfigureAwait(false); //System.Diagnostics.Debug.Write(data); data.Should().NotBeNullOrWhiteSpace(); data.Should().NotBeEmpty(); data.Should().StartWith("{"); data.Should().EndWith("}"); var rawSchema = Encoding.UTF8.GetString(TestResources.openapi_v3); var resolver = new JSchemaUrlResolver(); var schema = JSchema.Parse(rawSchema, resolver); var json = JObject.Parse(data); IList <ValidationError> errors = null; bool valid = json.IsValid(schema, out errors); valid.Should().BeTrue(); }
public IList <string> Validate() { if (string.IsNullOrEmpty(SchemaPath) || string.IsNullOrEmpty(jsonFullFileName)) { return(null); } IList <string> errors = new List <string>(); // using (StreamReader reader = File.OpenText(@"C:\Users\dhedayati\Documents\Visual Studio 2017\Projects\Repos\JsonValid\JsonValid\BDPSchema\business.json")) var parentSchema = Path.Combine(SchemaPath, "business.json"); if (!File.Exists(parentSchema)) { //System.Windows.MessageBox.Show("Schema file cannot be found.","Error"); errors.Add("Schema file cannot be found"); return(errors); } using (StreamReader reader = File.OpenText(@"C:\Users\dhedayati\Documents\Visual Studio 2017\Projects\Repos\JsonValid\JsonValid\BDPSchema\business.json")) { using (JsonTextReader jsonReader = new JsonTextReader(reader)) { JSchemaUrlResolver resolver = new JSchemaUrlResolver(); JSchema schema = JSchema.Load(jsonReader, new JSchemaReaderSettings() { Resolver = resolver, //BaseUri = new Uri(@"file://C:/Users/dhedayati/Documents/Visual Studio 2017/Projects/Repos/JsonValid/JsonValid/BDPSchema/") BaseUri = new Uri(SchemaPath) }); string data = ReadJsonFile(); var jTok = JToken.Parse(data); jTok.IsValid(schema, out errors); } } return(errors); }
public void ResolveRelativeFilePaths_InvalidNestedRef() { ExceptionAssert.Throws<JSchemaReaderException>( () => { JSchemaUrlResolver resolver = new JSchemaUrlResolver(); TestHelpers.OpenSchemaFile(@"resources\schemas\custom\root_invalidnestedref.json", resolver); }, "Could not resolve schema reference 'sub/sub2.json#/definitions/invalid'. Path 'properties.property2', line 7, position 23."); }
public void ResolveRelativeFilePaths() { JSchemaUrlResolver resolver = new JSchemaUrlResolver(); JSchema rootSchema = TestHelpers.OpenSchemaFile(@"resources\schemas\custom\root.json", resolver); Assert.AreEqual("Root", rootSchema.Title); Assert.IsTrue(rootSchema.BaseUri.OriginalString.EndsWith("root.json")); JSchema sub1 = rootSchema.Properties["property1"]; Assert.AreEqual("Sub1", sub1.Title); Assert.IsTrue(sub1.BaseUri.OriginalString.EndsWith("sub1.json")); JSchema sub2 = rootSchema.Properties["property2"]; Assert.AreEqual("Sub2", sub2.Title); Assert.IsTrue(sub2.BaseUri.OriginalString.EndsWith("sub/sub2.json")); JSchema nestedSub3 = sub2.Properties["property1"]; JSchema sub2Def1 = rootSchema.Properties["property3"]; Assert.AreEqual("Def1", sub2Def1.Title); Assert.IsTrue(sub2Def1.BaseUri.OriginalString.EndsWith("sub/sub2.json")); JSchema sub3 = rootSchema.Properties["property4"]; Assert.AreEqual("Sub3", sub3.Title); Assert.IsTrue(sub3.BaseUri.OriginalString.EndsWith("sub3.json")); Assert.AreEqual(nestedSub3, sub3); }
public void Reference_InnerSchemaOfExternalSchema() { JSchemaUrlResolver resolver = new JSchemaUrlResolver(); JSchema cleanSchema = TestHelpers.OpenSchemaFile(@"resources\schemas\grunt-clean-task.json", resolver); JSchema fileFormatSchema = cleanSchema.AdditionalProperties.AnyOf[0]; Assert.NotNull(fileFormatSchema.BaseUri); Assert.AreEqual(true, fileFormatSchema.Properties.ContainsKey("files")); }