JamesNK / Newtonsoft.Json.Schema

Json.NET Schema is a powerful, complete and easy to use JSON Schema framework for .NET
http://www.newtonsoft.com/jsonschema
Other
247 stars 107 forks source link

Outputting a JSchema with another keyword next to the $ref keyword produces and invalid schema #286

Open sfwester opened 2 years ago

sfwester commented 2 years ago

From 2019-09 spec section 8.2.4.1

The "$ref" keyword is an applicator that is used to reference a statically identified schema. Its results are the results of the referenced schema. [[CREF9: Note that this definition of how the results are determined means that other keywords can appear alongside of "$ref" in the same schema object. ]]

I tried this out using Newtonsoft.Json.Schema 3.0.14 dotnet fiddle of the code below

using System;
using Newtonsoft.Json.Schema;

namespace Tinker
{
    class Program
    {
        static void Main(string[] args)
        {
            string refSchema = @"{
                ""type"": ""string""
            }";

            JSchemaPreloadedResolver resolver = new JSchemaPreloadedResolver();
            resolver.Add(new Uri("refSchema", UriKind.RelativeOrAbsolute), refSchema);

            JSchema mainSchema = JSchema.Parse(@"{
                ""$schema"": ""http://json-schema.org/draft-2019-09/schema"",
                ""title"": ""A Title"",
                ""$ref"": ""refSchema""
            }", resolver);

            Console.WriteLine(mainSchema);

            JSchema.Parse(mainSchema.ToString());
        }
    }
}

This program outputs

{
  "$schema": "http://json-schema.org/draft-2019-09/schema",
  "title": "A Title",
  "$ref": "#/$ref"
}

and then throws

Unhandled exception. Newtonsoft.Json.Schema.JSchemaReaderException: Could not resolve schema reference '#/$ref'. Path '', line 1, position 1.

I would expect it to produce a valid schema that can be reparsed.

It may be worth noting that the expected schema is up to the application developer and the schema author to agree on. See section 7.7.1.1 Distinguishing Among Multiple Values

The application programmer and the schema author need to agree on the usage.

So, ideally, the library would provide some options for how to deal with multiple values if the referenced schema also included the title keyword. e.g., prefer local or prefer referenced.

omaryrajaa commented 1 year ago

This is still encountered in 3.0.15 When are we expecting solution for this?