/// <inheritdoc /> public override JsonSchemaXsdMetadata AnalyzeSchema(JsonSchema schema, Uri uri) { JsonSchema = schema; Metadata = new JsonSchemaXsdMetadata() { SchemaOrigin = "Seres" }; if (JsonSchema.TryGetKeyword(out InfoKeyword info)) { var messageNameElement = info.Value.GetProperty("meldingsnavn"); var messageTypeNameElement = info.Value.GetProperty("modellnavn"); Metadata.MessageName = messageNameElement.ValueKind == JsonValueKind.Undefined ? "melding" : messageNameElement.GetString(); Metadata.MessageTypeName = messageTypeNameElement.ValueKind == JsonValueKind.Undefined ? null : messageNameElement.GetString(); } else { Metadata.MessageName = "melding"; } DetermineRootModel(JsonSchema); AnalyzeSchema(JsonPointer.Parse("#"), JsonSchema); return(Metadata); }
public object?TryDeserialize(ISerializer serializer, DeserializationContext context) { if (context.LocalValue.Type == JsonValueType.Object) { var jsonObj = context.LocalValue.Object; if (jsonObj.TryGetValue(Constants.RefKey, out var reference)) { Log.Serialization(() => "Found reference marker; setting up tracking..."); var location = JsonPointer.Parse(reference.String); context.SerializationMap.AddReference(location, context.CurrentLocation.CleanAndClone()); return(context.InferredType.Default()); } } var pair = new SerializationReference(context.CurrentLocation.CleanAndClone()); context.SerializationMap.Add(pair); var obj = serializer.Deserialize(context); pair.Object = obj; pair.DeserializationIsComplete = true; return(obj); }
public void ValidateReturnsValidOnUnknownFormat() { JsonSchemaOptions.OutputFormat = SchemaValidationOutputFormat.Hierarchy; var schema = new JsonSchema().Type(JsonSchemaType.String).Format(StringFormat.GetFormat("Int32")); var json = (JsonValue)"32"; var expected = new SchemaValidationResults { IsValid = true, RelativeLocation = JsonPointer.Parse("#"), InstanceLocation = JsonPointer.Parse("#"), NestedResults = new List <SchemaValidationResults> { new SchemaValidationResults { IsValid = true, RelativeLocation = JsonPointer.Parse("#/type"), InstanceLocation = JsonPointer.Parse("#"), Keyword = "type" }, new SchemaValidationResults { IsValid = true, RelativeLocation = JsonPointer.Parse("#/format"), InstanceLocation = JsonPointer.Parse("#"), Keyword = "format", AnnotationValue = "Int32" } } }; var results = schema.Validate(json); results.AssertValid(expected); }
public static void JsonPointer_Parse() { var str = ""; var sut = JsonPointer.Parse(str); Assert.Equal(new JsonPointer(), sut); str = "/"; sut = JsonPointer.Parse(str); Assert.Equal(sut, new JsonPointer("")); str = "//test"; sut = JsonPointer.Parse(str); Assert.Equal(new JsonPointer("", "test"), sut); str = "/test/"; sut = JsonPointer.Parse(str); Assert.Equal(new JsonPointer("test", ""), sut); str = "/test~1/"; sut = JsonPointer.Parse(str); Assert.Equal(new JsonPointer("test/", ""), sut); str = "/test~0/"; sut = JsonPointer.Parse(str); Assert.Equal(new JsonPointer("test~", ""), sut); str = "/test~0~1/"; sut = JsonPointer.Parse(str); Assert.Equal(new JsonPointer("test~/", ""), sut); }
/// <summary> /// Builds an object from a <see cref="JsonValue"/>. /// </summary> /// <param name="json">The <see cref="JsonValue"/> representation of the object.</param> /// <param name="serializer">The <see cref="JsonSerializer"/> instance to use for additional /// serialization of values.</param> public void FromJson(JsonValue json, JsonSerializer serializer) { var obj = json.Object; IsValid = obj["valid"].Boolean; var relativeLocation = obj.TryGetString("keywordLocation"); if (relativeLocation != null) { RelativeLocation = JsonPointer.Parse(relativeLocation); } var absoluteLocation = obj.TryGetString("absoluteKeywordLocation"); if (absoluteLocation != null) { AbsoluteLocation = new Uri(absoluteLocation); } var instanceLocation = obj.TryGetString("instanceLocation"); if (instanceLocation != null) { InstanceLocation = JsonPointer.Parse(instanceLocation); } Keyword = obj.TryGetString("keyword"); AnnotationValue = obj.TryGetString("annotation"); var nested = obj.TryGetArray("annotations") ?? obj.TryGetArray("errors"); if (nested != null) { NestedResults = nested.Select(serializer.Deserialize <SchemaValidationResults>).ToList(); } AdditionalInfo = obj.TryGetObject("additionalInfo"); }
private void _ResolveReference(SchemaValidationContext context) { var documentPath = context.BaseUri; var referenceParts = Reference.Split(new[] { '#' }, StringSplitOptions.None); var address = string.IsNullOrWhiteSpace(referenceParts[0]) ? documentPath?.OriginalString : referenceParts[0]; _resolvedFragment = referenceParts.Length > 1 ? JsonPointer.Parse(referenceParts[1]) : new JsonPointer(); if (!string.IsNullOrWhiteSpace(address)) { if (!Uri.TryCreate(address, UriKind.Absolute, out var absolute)) { address = context.Local.Id + address; } if (documentPath != null && !Uri.TryCreate(address, UriKind.Absolute, out absolute)) { var uriFolder = documentPath.OriginalString.EndsWith("/") ? documentPath : documentPath.GetParentUri(); absolute = new Uri(uriFolder, address); address = absolute.OriginalString; } _resolvedRoot = JsonSchemaRegistry.Get(address); } else { _resolvedRoot = context.Root; } _ResolveLocalReference(_resolvedRoot?.DocumentPath ?? context.BaseUri); }
public void ValidateReturnsInvalidOnUnknownFormat() { JsonSchemaOptions.AllowUnknownFormats = false; JsonSchemaOptions.OutputFormat = SchemaValidationOutputFormat.Hierarchy; var schema = new JsonSchema().Type(JsonSchemaType.String).Format(StringFormat.GetFormat("Int32")); var json = (JsonValue)"32"; var expected = new SchemaValidationResults { IsValid = false, RelativeLocation = JsonPointer.Parse("#/format"), InstanceLocation = JsonPointer.Parse("#"), Keyword = "format", AdditionalInfo = new JsonObject { ["format"] = "Int32", ["isKnownFormat"] = false } }; try { var results = schema.Validate(json); results.AssertInvalid(expected); } finally { JsonSchemaOptions.AllowUnknownFormats = true; } }
public void ValidateReturnsInvalidOnUnknownFormat() { var schema = new JsonSchema().Type(JsonSchemaType.String).Format("Int32"); var json = (JsonValue)"32"; var expected = new SchemaValidationResults { IsValid = false, RelativeLocation = JsonPointer.Parse("#/format"), InstanceLocation = JsonPointer.Parse("#"), Keyword = "format", ErrorMessage = "\"32\" is not in an acceptable \"Int32\" format.", AnnotationValue = "Int32", AdditionalInfo = new JsonObject { ["actual"] = "32", ["format"] = "Int32", ["isKnownFormat"] = false } }; var results = schema.Validate(json, new JsonSchemaOptions { OutputFormat = SchemaValidationOutputFormat.Detailed, AllowUnknownFormats = false }); results.AssertInvalid(expected); }
public void Example(string pointerString, JsonValue expected) { var target = new JsonObject { ["foo"] = new JsonArray { "bar", "baz" }, [""] = 0, ["a/b"] = 1, ["c%d"] = 2, ["e^f"] = 3, ["g|h"] = 4, ["i\\j"] = 5, ["k\"l"] = 6, [" "] = 7, ["m~n"] = 8, }; var pointer = JsonPointer.Parse(pointerString); var actual = pointer.Evaluate(target); if (actual.Error != null) { Console.WriteLine(actual.Error); } Assert.AreEqual(expected, actual.Result); }
public void ParseExpectUriEncodedGetPlain() { Assert.Throws <PointerParseException>(() => { JsonPointer.Parse("/one/2/three", JsonPointerKind.UriEncoded); }); }
public void Parse(string pointerString, string[] segments) { var pointer = JsonPointer.Parse(pointerString); pointer.Segments.Length.Should().Be(segments.Length); pointer.Segments.Select(s => s.Value).Should().BeEquivalentTo(segments); }
public void GettingLastItemInArray() { var target = new JsonObject { ["a"] = 1, ["b"] = new JsonArray { 5, true, null }, ["c"] = new JsonObject { ["0"] = false } }; var pointer = JsonPointer.Parse("/b/-"); var actual = pointer.Evaluate(target); if (actual.Error != null) { Console.WriteLine(actual.Error); } Assert.AreEqual(JsonValue.Null, actual.Result); }
public void IndexingAnObjectInterpretsIndexAsKey() { var target = new JsonObject { ["a"] = 1, ["b"] = new JsonArray { 5, true, null }, ["c"] = new JsonObject { ["0"] = false } }; var pointer = JsonPointer.Parse("/c/0"); var actual = pointer.Evaluate(target); if (actual.Error != null) { Console.WriteLine(actual.Error); } Assert.AreEqual((JsonValue)false, actual.Result); }
public object Deserialize(SerializationContext context) { if (context.LocalValue.Type == JsonValueType.Object) { var jsonObj = context.LocalValue.Object; if (jsonObj.TryGetValue(Constants.RefKey, out var reference)) { var location = JsonPointer.Parse(reference.String); context.SerializationMap.AddReference(location, context.CurrentLocation); return(context.InferredType.Default()); } } var pair = new SerializationReference { Source = context.CurrentLocation }; context.SerializationMap.Add(pair); var obj = _innerSerializer.Deserialize(context); pair.Object = obj; pair.DeserializationIsComplete = true; return(obj); }
private void _ResolveReference(SchemaValidationContext context) { if (context.RecursiveAnchor != null) { var baseDocument = JsonSchemaRegistry.Get(context.BaseUri.OriginalString); if (baseDocument?.Get <RecursiveAnchorKeyword>() != null) { _resolvedRoot = context.RecursiveAnchor; } } if (Reference.IsLocalSchemaId()) { Resolved = context.LocalRegistry.GetLocal(Reference); if (Resolved != null) { return; } } var documentPath = _resolvedRoot?.DocumentPath ?? context.BaseUri; var referenceParts = Reference.Split(new[] { '#' }, StringSplitOptions.None); var address = string.IsNullOrWhiteSpace(referenceParts[0]) ? documentPath?.OriginalString : referenceParts[0]; _resolvedFragment = referenceParts.Length > 1 ? JsonPointer.Parse(referenceParts[1]) : new JsonPointer(); if (_resolvedRoot == null) { if (!string.IsNullOrWhiteSpace(address)) { if (!Uri.TryCreate(address, UriKind.Absolute, out var absolute)) { address = context.Local.Id + address; } if (documentPath != null && !Uri.TryCreate(address, UriKind.Absolute, out absolute)) { var uriFolder = documentPath.OriginalString.EndsWith("/") ? documentPath : documentPath.GetParentUri(); absolute = new Uri(uriFolder, address); address = absolute.OriginalString; } _resolvedRoot = JsonSchemaRegistry.Get(address); } else { _resolvedRoot = context.Root; } } var wellKnown = JsonSchemaRegistry.GetWellKnown(Reference); if (wellKnown != null) { Resolved = wellKnown; return; } _ResolveLocalReference(_resolvedRoot?.DocumentPath ?? context.BaseUri); }
public static void Reference_ParseUrl_Absolute() { var sut = OasReference.ParseUrl(new Uri("http://example.com/openapi.json#/test/path")); Assert.Equal("http://example.com/openapi.json", sut.Url.ToString()); Assert.Equal(JsonPointer.Parse("/test/path"), sut.Pointer); Assert.Equal("http://example.com/openapi.json#/test/path", sut.ToString()); }
public static void FieldExpression_Parse_RequestBody() { var sut = OasFieldExpression.Parse("$request.body#/foo/bar"); Assert.Equal(OasFieldExpressionType.Request, sut.ExpressionType); Assert.Equal(OasFieldExpressionSource.Body, sut.ExpressionSource); Assert.Equal(JsonPointer.Parse("/foo/bar"), sut.Pointer); Assert.Equal("$request.body#/foo/bar", sut.ToString()); }
/// <summary> /// Recursively analyzes all schemas for the provided keyword. /// </summary> /// <param name="path"><see cref="JsonPointer"/> representing the actual path to the keyword being provided.</param> /// <param name="keyword">The keyword to be analyzed.</param> protected void AnalyzeKeyword(JsonPointer path, IJsonSchemaKeyword keyword) { switch (keyword) { case AllOfKeyword item: for (var i = 0; i < item.Schemas.Count; i++) { AnalyzeSchema(path.Combine(JsonPointer.Parse($"/[{i}]")), item.Schemas[i]); } break; case AnyOfKeyword item: for (var i = 0; i < item.Schemas.Count; i++) { AnalyzeSchema(path.Combine(JsonPointer.Parse($"/[{i}]")), item.Schemas[i]); } break; case OneOfKeyword item: for (var i = 0; i < item.Schemas.Count; i++) { AnalyzeSchema(path.Combine(JsonPointer.Parse($"/[{i}]")), item.Schemas[i]); } break; case DefinitionsKeyword item: foreach (var(name, definition) in item.Definitions) { AnalyzeSchema(path.Combine(JsonPointer.Parse($"/{name}")), definition); } break; case DefsKeyword item: foreach (var(name, definition) in item.Definitions) { AnalyzeSchema(path.Combine(JsonPointer.Parse($"/{name}")), definition); } break; case PropertiesKeyword item: foreach (var(name, definition) in item.Properties) { AnalyzeSchema(path.Combine(JsonPointer.Parse($"/{name}")), definition); } break; case ISchemaContainer schemaContainer: AnalyzeSchema(path, schemaContainer.Schema); break; } }
public void Errors(string pointerString) { using var target = JsonDocument.Parse("{\"a\":\"1\",\"b\":[5, true, null],\"c\":{\"false\":false}}"); var pointer = JsonPointer.Parse(pointerString); var actual = pointer.Evaluate(target.RootElement); Assert.IsNull(actual); }
public void IndexingAnObjectInterpretsIndexAsKey() { using var target = JsonDocument.Parse("{\"a\":\"1\",\"b\":[5, true, null],\"c\":{\"0\":false}}"); var pointer = JsonPointer.Parse("/c/0"); var actual = pointer.Evaluate(target.RootElement); // ReSharper disable once PossibleInvalidOperationException Assert.AreEqual(false, actual.Value.GetBoolean()); }
public void GettingLastItemInArray() { using var target = JsonDocument.Parse("{\"a\":\"1\",\"b\":[5, true, null],\"c\":{\"0\":false}}"); var pointer = JsonPointer.Parse("/b/-"); var actual = pointer.Evaluate(target.RootElement); // ReSharper disable once PossibleInvalidOperationException Assert.AreEqual(JsonValueKind.Null, actual.Value.ValueKind); }
private void ProcessRefKeyword(JsonPointer path, RefKeyword keyword, SchemaContext context) { int subSchemaIndex = 0; foreach (var subSchema in keyword.GetSubschemas()) { var subSchemaPath = path.Combine(JsonPointer.Parse($"/[{subSchemaIndex}]")); ProcessSubSchema(subSchemaPath, subSchema, context); subSchemaIndex++; } }
public async Task IsValidNillableAttribute_NillableAttribute_ShouldReturnTrue(string path, string jsonPointer, string testCase) { _testOutputHelper.WriteLine($"{testCase}"); var schema = await ResourceHelpers.LoadJsonSchemaTestData(path); var analyzer = new SeresJsonSchemaAnalyzer(); var results = analyzer.AnalyzeSchema(schema, new Uri("dummy", UriKind.Relative)); results.GetCompatibleTypes(JsonPointer.Parse(jsonPointer)).Should().Contain(CompatibleXsdType.Nillable); }
public static void JsonPointer_Evaluate() { var json = JToken.Parse(@" { ""foo"": [""bar"", ""baz""], """": 0, ""a/b"": 1, ""c%d"": 2, ""e^f"": 3, ""g|h"": 4, ""i\\j"": 5, ""k\""l"": 6, "" "": 7, ""m~n"": 8 }"); var result = JsonPointer.Parse("").Evaluate(json); Assert.Equal(json, result); result = JsonPointer.Parse("/foo").Evaluate(json); Assert.Equal(new[] { "bar", "baz" }, ((JArray)result).Select(x => (string)x).ToArray()); result = JsonPointer.Parse("/foo/0").Evaluate(json); Assert.Equal("bar", result); result = JsonPointer.Parse("/").Evaluate(json); Assert.Equal(0, (int)result); result = JsonPointer.Parse("/a~1b").Evaluate(json); Assert.Equal(1, (int)result); result = JsonPointer.Parse("/c%d").Evaluate(json); Assert.Equal(2, (int)result); result = JsonPointer.Parse("/e^f").Evaluate(json); Assert.Equal(3, (int)result); result = JsonPointer.Parse("/g|h").Evaluate(json); Assert.Equal(4, (int)result); result = JsonPointer.Parse("/i\\j").Evaluate(json); Assert.Equal(5, (int)result); result = JsonPointer.Parse("/k\"l").Evaluate(json); Assert.Equal(6, (int)result); result = JsonPointer.Parse("/ ").Evaluate(json); Assert.Equal(7, (int)result); result = JsonPointer.Parse("/m~0n").Evaluate(json); Assert.Equal(8, (int)result); }
private JsonPatchResult _Move(JsonValue json) { // TODO: This isn't the most efficient way to do this, but it'll get the job done. if (JsonPointer.Parse(From !).Equals(JsonPointer.Parse(Path))) { return(new JsonPatchResult(json)); } var copy = _Copy(json); return(!copy.Success ? copy : _RemoveAtPath(json, From !)); }
public async Task Analyze_SimpleContent_Extension(string path) { JsonSchemaKeywords.RegisterXsdKeywords(); var schema = await ResourceHelpers.LoadJsonSchemaTestData(path); var analyzer = new SeresJsonSchemaAnalyzer(); var metadata = analyzer.AnalyzeSchema(schema, new Uri("dummy", UriKind.Relative)); metadata.GetCompatibleTypes(JsonPointer.Parse("#/$defs/myBase")).Should().Contain(new[] { CompatibleXsdType.ComplexType, CompatibleXsdType.SimpleContentExtension }); }
public static void JsonPointer_Evaluate_Errors() { var json = JToken.Parse(@" { ""foo1"": 123, ""foo2"": true, ""foo3"": false, ""foo4"": ""value"", ""foo5"": null, ""foo6"": [""bar"", ""baz""], ""foo7"": { ""foo1"": 123, ""foo2"": true, ""foo3"": false, ""foo4"": ""value"", ""foo5"": null, ""foo6"": [""bar"", ""baz""], ""foo7"": { ""foo1"": 123, ""foo2"": true, ""foo3"": false, ""foo4"": ""value"", ""foo5"": null, ""foo6"": [""bar"", ""baz""], } } }"); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo0").Evaluate(json)); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo1/foo1").Evaluate(json)); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo2/foo1").Evaluate(json)); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo3/foo1").Evaluate(json)); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo4/foo1").Evaluate(json)); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo5/foo1").Evaluate(json)); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo6/foo1").Evaluate(json)); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo7/foo0").Evaluate(json)); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo7/foo7/foo0").Evaluate(json)); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo6/2").Evaluate(json)); Assert.Throws <InvalidOperationException>(() => JsonPointer.Parse("/foo6/-").Evaluate(json)); JsonPointer.Parse("/foo0").Evaluate(json, JsonPointerEvaluationOptions.MissingMembersAreNull); JsonPointer.Parse("/foo1/foo1").Evaluate(json, JsonPointerEvaluationOptions.PrimitiveMembersAndIndiciesAreNull); JsonPointer.Parse("/foo2/foo1").Evaluate(json, JsonPointerEvaluationOptions.PrimitiveMembersAndIndiciesAreNull); JsonPointer.Parse("/foo3/foo1").Evaluate(json, JsonPointerEvaluationOptions.PrimitiveMembersAndIndiciesAreNull); JsonPointer.Parse("/foo4/foo1").Evaluate(json, JsonPointerEvaluationOptions.PrimitiveMembersAndIndiciesAreNull); JsonPointer.Parse("/foo5/foo1").Evaluate(json, JsonPointerEvaluationOptions.NullCoalescing); JsonPointer.Parse("/foo6/foo1").Evaluate(json, JsonPointerEvaluationOptions.ArrayMembersAreNull); JsonPointer.Parse("/foo7/foo0").Evaluate(json, JsonPointerEvaluationOptions.MissingMembersAreNull); JsonPointer.Parse("/foo7/foo0/foo0").Evaluate(json, JsonPointerEvaluationOptions.MissingMembersAreNull | JsonPointerEvaluationOptions.NullCoalescing); JsonPointer.Parse("/foo6/2").Evaluate(json, JsonPointerEvaluationOptions.InvalidIndiciesAreNull); JsonPointer.Parse("/foo6/-").Evaluate(json, JsonPointerEvaluationOptions.InvalidIndiciesAreNull); }
/// <inheritdoc/> public override JsonSchemaXsdMetadata AnalyzeSchema(JsonSchema schema, Uri uri) { JsonSchema = schema; Metadata = new JsonSchemaXsdMetadata { SchemaOrigin = "Standard", MessageName = UrlHelper.GetName(uri.ToString()), MessageTypeName = string.Empty }; DetermineRootModel(JsonSchema); AnalyzeSchema(JsonPointer.Parse("#"), JsonSchema); return(Metadata); }
public async Task Analyze_Seres_Converted_JsonSchema(string path) { JsonSchemaKeywords.RegisterXsdKeywords(); var schema = await ResourceHelpers.LoadJsonSchemaTestData(path); var analyzer = new SeresJsonSchemaAnalyzer(); var metadata = analyzer.AnalyzeSchema(schema, new Uri("dummy", UriKind.Relative)); metadata.GetCompatibleTypes(JsonPointer.Parse("#")).Should().Equal(CompatibleXsdType.ComplexType); metadata.GetCompatibleTypes(JsonPointer.Parse("#/oneOf/[0]")).Should().Equal(CompatibleXsdType.ComplexType); metadata.GetCompatibleTypes(JsonPointer.Parse("#/$defs/melding-modell")).Should().Equal(CompatibleXsdType.ComplexType); metadata.GetCompatibleTypes(JsonPointer.Parse("#/$defs/melding-modell/properties/e1")).Should().Equal(CompatibleXsdType.SimpleType); }
private void ProcessSchema(JsonSchema schema) { var rootPath = JsonPointer.Parse("#"); var name = ConvertToCSharpCompatibleName(ModelName); var context = new SchemaContext() { Id = name, ParentId = string.Empty, Name = name, XPath = "/" }; foreach (var keyword in schema.Keywords) { var keywordPath = rootPath.Combine(JsonPointer.Parse($"/{keyword.Keyword()}")); ProcessKeyword(keywordPath, keyword, context); } }