RicoSuter/NJsonSchema

JsonSchemaValidator generate ValidationError on nullable string

Open

#865 opened on Jan 8, 2019

View on GitHub
 (5 comments) (0 reactions) (0 assignees)C# (550 forks)github user discovery
help wantedtype: enhancement

Repository metrics

Stars
 (1,578 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

Hi,

When i try to validate a json input against a json schema from swagger document, validation error occured for nullable string but i'm not sure if it's correct result.

How can i accept nullable string using JsonSchemaValidator/JsonSchema4 ?

    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using NJsonSchema;
    using NJsonSchema.Validation;
    using NSwag;
    using NUnit.Framework;

    [TestFixture]
    public class NullableTypeTests
    {

        [Test]
        public async Task Validation_Should_Have_No_Error_With_Nullable_String()
        {
            string openApiDocumentContent = @"
openapi: 3.0.0

components:
  schemas:
    SomeObject:
      type: object
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
          nullable: true
";

            SwaggerDocument swaggerDocument =
                await SwaggerYamlDocument.FromYamlAsync(openApiDocumentContent, null, SchemaType.OpenApi3);

            Assert.That(swaggerDocument, Is.Not.Null);

            JsonSchema4 jsonSchema4 = null;

            if (swaggerDocument?.Components?.Schemas != null)
            {
                if (!swaggerDocument.Components.Schemas.TryGetValue("SomeObject", out jsonSchema4))
                {
                    jsonSchema4 = null;
                }
            }

            Assert.That(jsonSchema4, Is.Not.Null);

            string input = @"
{
  ""id"": 123456,
  ""name"": null
}";
            JsonSchemaValidator jsonSchemaValidator = new JsonSchemaValidator();
            ICollection<ValidationError> validationResult =
                jsonSchemaValidator.Validate(input, jsonSchema4);

            Assert.That(validationResult, Is.Empty, JsonConvert.SerializeObject(validationResult));
        }
    }

Contributor guide