-Line endings
This commit is contained in:
@@ -1,104 +1,104 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Contains the JSON schema extension methods.
|
||||
/// </summary>
|
||||
public static class Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether the <see cref="JToken"/> is valid.
|
||||
/// </summary>
|
||||
/// <param name="source">The source <see cref="JToken"/> to test.</param>
|
||||
/// <param name="schema">The schema to test with.</param>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>.
|
||||
/// </returns>
|
||||
public static bool IsValid(this JToken source, JsonSchema schema)
|
||||
{
|
||||
bool valid = true;
|
||||
source.Validate(schema, (sender, args) => { valid = false; });
|
||||
return valid;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the <see cref="JToken"/> is valid.
|
||||
/// </summary>
|
||||
/// <param name="source">The source <see cref="JToken"/> to test.</param>
|
||||
/// <param name="schema">The schema to test with.</param>
|
||||
/// <param name="errorMessages">When this method returns, contains any error messages generated while validating. </param>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>.
|
||||
/// </returns>
|
||||
public static bool IsValid(this JToken source, JsonSchema schema, out IList<string> errorMessages)
|
||||
{
|
||||
IList<string> errors = new List<string>();
|
||||
|
||||
source.Validate(schema, (sender, args) => errors.Add(args.Message));
|
||||
|
||||
errorMessages = errors;
|
||||
return (errorMessages.Count == 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the specified <see cref="JToken"/>.
|
||||
/// </summary>
|
||||
/// <param name="source">The source <see cref="JToken"/> to test.</param>
|
||||
/// <param name="schema">The schema to test with.</param>
|
||||
public static void Validate(this JToken source, JsonSchema schema)
|
||||
{
|
||||
source.Validate(schema, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the specified <see cref="JToken"/>.
|
||||
/// </summary>
|
||||
/// <param name="source">The source <see cref="JToken"/> to test.</param>
|
||||
/// <param name="schema">The schema to test with.</param>
|
||||
/// <param name="validationEventHandler">The validation event handler.</param>
|
||||
public static void Validate(this JToken source, JsonSchema schema, ValidationEventHandler validationEventHandler)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(source, "source");
|
||||
ValidationUtils.ArgumentNotNull(schema, "schema");
|
||||
|
||||
using (JsonValidatingReader reader = new JsonValidatingReader(source.CreateReader()))
|
||||
{
|
||||
reader.Schema = schema;
|
||||
if (validationEventHandler != null)
|
||||
reader.ValidationEventHandler += validationEventHandler;
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Contains the JSON schema extension methods.
|
||||
/// </summary>
|
||||
public static class Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether the <see cref="JToken"/> is valid.
|
||||
/// </summary>
|
||||
/// <param name="source">The source <see cref="JToken"/> to test.</param>
|
||||
/// <param name="schema">The schema to test with.</param>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>.
|
||||
/// </returns>
|
||||
public static bool IsValid(this JToken source, JsonSchema schema)
|
||||
{
|
||||
bool valid = true;
|
||||
source.Validate(schema, (sender, args) => { valid = false; });
|
||||
return valid;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the <see cref="JToken"/> is valid.
|
||||
/// </summary>
|
||||
/// <param name="source">The source <see cref="JToken"/> to test.</param>
|
||||
/// <param name="schema">The schema to test with.</param>
|
||||
/// <param name="errorMessages">When this method returns, contains any error messages generated while validating. </param>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>.
|
||||
/// </returns>
|
||||
public static bool IsValid(this JToken source, JsonSchema schema, out IList<string> errorMessages)
|
||||
{
|
||||
IList<string> errors = new List<string>();
|
||||
|
||||
source.Validate(schema, (sender, args) => errors.Add(args.Message));
|
||||
|
||||
errorMessages = errors;
|
||||
return (errorMessages.Count == 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the specified <see cref="JToken"/>.
|
||||
/// </summary>
|
||||
/// <param name="source">The source <see cref="JToken"/> to test.</param>
|
||||
/// <param name="schema">The schema to test with.</param>
|
||||
public static void Validate(this JToken source, JsonSchema schema)
|
||||
{
|
||||
source.Validate(schema, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the specified <see cref="JToken"/>.
|
||||
/// </summary>
|
||||
/// <param name="source">The source <see cref="JToken"/> to test.</param>
|
||||
/// <param name="schema">The schema to test with.</param>
|
||||
/// <param name="validationEventHandler">The validation event handler.</param>
|
||||
public static void Validate(this JToken source, JsonSchema schema, ValidationEventHandler validationEventHandler)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(source, "source");
|
||||
ValidationUtils.ArgumentNotNull(schema, "schema");
|
||||
|
||||
using (JsonValidatingReader reader = new JsonValidatingReader(source.CreateReader()))
|
||||
{
|
||||
reader.Schema = schema;
|
||||
if (validationEventHandler != null)
|
||||
reader.ValidationEventHandler += validationEventHandler;
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,296 +1,296 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// An in-memory representation of a JSON Schema.
|
||||
/// </summary>
|
||||
public class JsonSchema
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the id.
|
||||
/// </summary>
|
||||
public string Id { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the title.
|
||||
/// </summary>
|
||||
public string Title { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the object is required.
|
||||
/// </summary>
|
||||
public bool? Required { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the object is read only.
|
||||
/// </summary>
|
||||
public bool? ReadOnly { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the object is visible to users.
|
||||
/// </summary>
|
||||
public bool? Hidden { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the object is transient.
|
||||
/// </summary>
|
||||
public bool? Transient { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the description of the object.
|
||||
/// </summary>
|
||||
public string Description { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the types of values allowed by the object.
|
||||
/// </summary>
|
||||
/// <value>The type.</value>
|
||||
public JsonSchemaType? Type { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the pattern.
|
||||
/// </summary>
|
||||
/// <value>The pattern.</value>
|
||||
public string Pattern { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the minimum length.
|
||||
/// </summary>
|
||||
/// <value>The minimum length.</value>
|
||||
public int? MinimumLength { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum length.
|
||||
/// </summary>
|
||||
/// <value>The maximum length.</value>
|
||||
public int? MaximumLength { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a number that the value should be divisble by.
|
||||
/// </summary>
|
||||
/// <value>A number that the value should be divisble by.</value>
|
||||
public double? DivisibleBy { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the minimum.
|
||||
/// </summary>
|
||||
/// <value>The minimum.</value>
|
||||
public double? Minimum { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum.
|
||||
/// </summary>
|
||||
/// <value>The maximum.</value>
|
||||
public double? Maximum { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a flag indicating whether the value can not equal the number defined by the "minimum" attribute.
|
||||
/// </summary>
|
||||
/// <value>A flag indicating whether the value can not equal the number defined by the "minimum" attribute.</value>
|
||||
public bool? ExclusiveMinimum { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a flag indicating whether the value can not equal the number defined by the "maximum" attribute.
|
||||
/// </summary>
|
||||
/// <value>A flag indicating whether the value can not equal the number defined by the "maximum" attribute.</value>
|
||||
public bool? ExclusiveMaximum { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the minimum number of items.
|
||||
/// </summary>
|
||||
/// <value>The minimum number of items.</value>
|
||||
public int? MinimumItems { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum number of items.
|
||||
/// </summary>
|
||||
/// <value>The maximum number of items.</value>
|
||||
public int? MaximumItems { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="JsonSchema"/> of items.
|
||||
/// </summary>
|
||||
/// <value>The <see cref="JsonSchema"/> of items.</value>
|
||||
public IList<JsonSchema> Items { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="JsonSchema"/> of properties.
|
||||
/// </summary>
|
||||
/// <value>The <see cref="JsonSchema"/> of properties.</value>
|
||||
public IDictionary<string, JsonSchema> Properties { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="JsonSchema"/> of additional properties.
|
||||
/// </summary>
|
||||
/// <value>The <see cref="JsonSchema"/> of additional properties.</value>
|
||||
public JsonSchema AdditionalProperties { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the pattern properties.
|
||||
/// </summary>
|
||||
/// <value>The pattern properties.</value>
|
||||
public IDictionary<string, JsonSchema> PatternProperties { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether additional properties are allowed.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if additional properties are allowed; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
public bool AllowAdditionalProperties { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the required property if this property is present.
|
||||
/// </summary>
|
||||
/// <value>The required property if this property is present.</value>
|
||||
public string Requires { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the identity.
|
||||
/// </summary>
|
||||
/// <value>The identity.</value>
|
||||
public IList<string> Identity { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the a collection of valid enum values allowed.
|
||||
/// </summary>
|
||||
/// <value>A collection of valid enum values allowed.</value>
|
||||
public IList<JToken> Enum { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a collection of options.
|
||||
/// </summary>
|
||||
/// <value>A collection of options.</value>
|
||||
public IDictionary<JToken, string> Options { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets disallowed types.
|
||||
/// </summary>
|
||||
/// <value>The disallow types.</value>
|
||||
public JsonSchemaType? Disallow { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the default value.
|
||||
/// </summary>
|
||||
/// <value>The default value.</value>
|
||||
public JToken Default { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the extend <see cref="JsonSchema"/>.
|
||||
/// </summary>
|
||||
/// <value>The extended <see cref="JsonSchema"/>.</value>
|
||||
public JsonSchema Extends { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the format.
|
||||
/// </summary>
|
||||
/// <value>The format.</value>
|
||||
public string Format { get; set; }
|
||||
|
||||
private readonly string _internalId = Guid.NewGuid().ToString("N");
|
||||
|
||||
internal string InternalId
|
||||
{
|
||||
get { return _internalId; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchema"/> class.
|
||||
/// </summary>
|
||||
public JsonSchema()
|
||||
{
|
||||
AllowAdditionalProperties = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a <see cref="JsonSchema"/> from the specified <see cref="JsonReader"/>.
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="JsonReader"/> containing the JSON Schema to read.</param>
|
||||
/// <returns>The <see cref="JsonSchema"/> object representing the JSON Schema.</returns>
|
||||
public static JsonSchema Read(JsonReader reader)
|
||||
{
|
||||
return Read(reader, new JsonSchemaResolver());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a <see cref="JsonSchema"/> from the specified <see cref="JsonReader"/>.
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="JsonReader"/> containing the JSON Schema to read.</param>
|
||||
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> to use when resolving schema references.</param>
|
||||
/// <returns>The <see cref="JsonSchema"/> object representing the JSON Schema.</returns>
|
||||
public static JsonSchema Read(JsonReader reader, JsonSchemaResolver resolver)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(reader, "reader");
|
||||
ValidationUtils.ArgumentNotNull(resolver, "resolver");
|
||||
|
||||
JsonSchemaBuilder builder = new JsonSchemaBuilder(resolver);
|
||||
return builder.Parse(reader);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Load a <see cref="JsonSchema"/> from a string that contains schema JSON.
|
||||
/// </summary>
|
||||
/// <param name="json">A <see cref="String"/> that contains JSON.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> populated from the string that contains JSON.</returns>
|
||||
public static JsonSchema Parse(string json)
|
||||
{
|
||||
return Parse(json, new JsonSchemaResolver());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the specified json.
|
||||
/// </summary>
|
||||
/// <param name="json">The json.</param>
|
||||
/// <param name="resolver">The resolver.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> populated from the string that contains JSON.</returns>
|
||||
public static JsonSchema Parse(string json, JsonSchemaResolver resolver)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(json, "json");
|
||||
|
||||
JsonReader reader = new JsonTextReader(new StringReader(json));
|
||||
|
||||
return Read(reader, resolver);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes this schema to a <see cref="JsonWriter"/>.
|
||||
/// </summary>
|
||||
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
|
||||
public void WriteTo(JsonWriter writer)
|
||||
{
|
||||
WriteTo(writer, new JsonSchemaResolver());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes this schema to a <see cref="JsonWriter"/> using the specified <see cref="JsonSchemaResolver"/>.
|
||||
/// </summary>
|
||||
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
|
||||
/// <param name="resolver">The resolver used.</param>
|
||||
public void WriteTo(JsonWriter writer, JsonSchemaResolver resolver)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(writer, "writer");
|
||||
ValidationUtils.ArgumentNotNull(resolver, "resolver");
|
||||
|
||||
JsonSchemaWriter schemaWriter = new JsonSchemaWriter(writer, resolver);
|
||||
schemaWriter.WriteSchema(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
|
||||
/// </returns>
|
||||
public override string ToString()
|
||||
{
|
||||
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
|
||||
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
|
||||
jsonWriter.Formatting = Formatting.Indented;
|
||||
|
||||
WriteTo(jsonWriter);
|
||||
|
||||
return writer.ToString();
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// An in-memory representation of a JSON Schema.
|
||||
/// </summary>
|
||||
public class JsonSchema
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the id.
|
||||
/// </summary>
|
||||
public string Id { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the title.
|
||||
/// </summary>
|
||||
public string Title { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the object is required.
|
||||
/// </summary>
|
||||
public bool? Required { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the object is read only.
|
||||
/// </summary>
|
||||
public bool? ReadOnly { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the object is visible to users.
|
||||
/// </summary>
|
||||
public bool? Hidden { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the object is transient.
|
||||
/// </summary>
|
||||
public bool? Transient { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the description of the object.
|
||||
/// </summary>
|
||||
public string Description { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the types of values allowed by the object.
|
||||
/// </summary>
|
||||
/// <value>The type.</value>
|
||||
public JsonSchemaType? Type { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the pattern.
|
||||
/// </summary>
|
||||
/// <value>The pattern.</value>
|
||||
public string Pattern { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the minimum length.
|
||||
/// </summary>
|
||||
/// <value>The minimum length.</value>
|
||||
public int? MinimumLength { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum length.
|
||||
/// </summary>
|
||||
/// <value>The maximum length.</value>
|
||||
public int? MaximumLength { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a number that the value should be divisble by.
|
||||
/// </summary>
|
||||
/// <value>A number that the value should be divisble by.</value>
|
||||
public double? DivisibleBy { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the minimum.
|
||||
/// </summary>
|
||||
/// <value>The minimum.</value>
|
||||
public double? Minimum { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum.
|
||||
/// </summary>
|
||||
/// <value>The maximum.</value>
|
||||
public double? Maximum { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a flag indicating whether the value can not equal the number defined by the "minimum" attribute.
|
||||
/// </summary>
|
||||
/// <value>A flag indicating whether the value can not equal the number defined by the "minimum" attribute.</value>
|
||||
public bool? ExclusiveMinimum { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a flag indicating whether the value can not equal the number defined by the "maximum" attribute.
|
||||
/// </summary>
|
||||
/// <value>A flag indicating whether the value can not equal the number defined by the "maximum" attribute.</value>
|
||||
public bool? ExclusiveMaximum { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the minimum number of items.
|
||||
/// </summary>
|
||||
/// <value>The minimum number of items.</value>
|
||||
public int? MinimumItems { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum number of items.
|
||||
/// </summary>
|
||||
/// <value>The maximum number of items.</value>
|
||||
public int? MaximumItems { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="JsonSchema"/> of items.
|
||||
/// </summary>
|
||||
/// <value>The <see cref="JsonSchema"/> of items.</value>
|
||||
public IList<JsonSchema> Items { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="JsonSchema"/> of properties.
|
||||
/// </summary>
|
||||
/// <value>The <see cref="JsonSchema"/> of properties.</value>
|
||||
public IDictionary<string, JsonSchema> Properties { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="JsonSchema"/> of additional properties.
|
||||
/// </summary>
|
||||
/// <value>The <see cref="JsonSchema"/> of additional properties.</value>
|
||||
public JsonSchema AdditionalProperties { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the pattern properties.
|
||||
/// </summary>
|
||||
/// <value>The pattern properties.</value>
|
||||
public IDictionary<string, JsonSchema> PatternProperties { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether additional properties are allowed.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if additional properties are allowed; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
public bool AllowAdditionalProperties { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the required property if this property is present.
|
||||
/// </summary>
|
||||
/// <value>The required property if this property is present.</value>
|
||||
public string Requires { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the identity.
|
||||
/// </summary>
|
||||
/// <value>The identity.</value>
|
||||
public IList<string> Identity { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the a collection of valid enum values allowed.
|
||||
/// </summary>
|
||||
/// <value>A collection of valid enum values allowed.</value>
|
||||
public IList<JToken> Enum { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a collection of options.
|
||||
/// </summary>
|
||||
/// <value>A collection of options.</value>
|
||||
public IDictionary<JToken, string> Options { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets disallowed types.
|
||||
/// </summary>
|
||||
/// <value>The disallow types.</value>
|
||||
public JsonSchemaType? Disallow { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the default value.
|
||||
/// </summary>
|
||||
/// <value>The default value.</value>
|
||||
public JToken Default { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the extend <see cref="JsonSchema"/>.
|
||||
/// </summary>
|
||||
/// <value>The extended <see cref="JsonSchema"/>.</value>
|
||||
public JsonSchema Extends { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the format.
|
||||
/// </summary>
|
||||
/// <value>The format.</value>
|
||||
public string Format { get; set; }
|
||||
|
||||
private readonly string _internalId = Guid.NewGuid().ToString("N");
|
||||
|
||||
internal string InternalId
|
||||
{
|
||||
get { return _internalId; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchema"/> class.
|
||||
/// </summary>
|
||||
public JsonSchema()
|
||||
{
|
||||
AllowAdditionalProperties = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a <see cref="JsonSchema"/> from the specified <see cref="JsonReader"/>.
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="JsonReader"/> containing the JSON Schema to read.</param>
|
||||
/// <returns>The <see cref="JsonSchema"/> object representing the JSON Schema.</returns>
|
||||
public static JsonSchema Read(JsonReader reader)
|
||||
{
|
||||
return Read(reader, new JsonSchemaResolver());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a <see cref="JsonSchema"/> from the specified <see cref="JsonReader"/>.
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="JsonReader"/> containing the JSON Schema to read.</param>
|
||||
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> to use when resolving schema references.</param>
|
||||
/// <returns>The <see cref="JsonSchema"/> object representing the JSON Schema.</returns>
|
||||
public static JsonSchema Read(JsonReader reader, JsonSchemaResolver resolver)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(reader, "reader");
|
||||
ValidationUtils.ArgumentNotNull(resolver, "resolver");
|
||||
|
||||
JsonSchemaBuilder builder = new JsonSchemaBuilder(resolver);
|
||||
return builder.Parse(reader);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Load a <see cref="JsonSchema"/> from a string that contains schema JSON.
|
||||
/// </summary>
|
||||
/// <param name="json">A <see cref="String"/> that contains JSON.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> populated from the string that contains JSON.</returns>
|
||||
public static JsonSchema Parse(string json)
|
||||
{
|
||||
return Parse(json, new JsonSchemaResolver());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the specified json.
|
||||
/// </summary>
|
||||
/// <param name="json">The json.</param>
|
||||
/// <param name="resolver">The resolver.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> populated from the string that contains JSON.</returns>
|
||||
public static JsonSchema Parse(string json, JsonSchemaResolver resolver)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(json, "json");
|
||||
|
||||
JsonReader reader = new JsonTextReader(new StringReader(json));
|
||||
|
||||
return Read(reader, resolver);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes this schema to a <see cref="JsonWriter"/>.
|
||||
/// </summary>
|
||||
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
|
||||
public void WriteTo(JsonWriter writer)
|
||||
{
|
||||
WriteTo(writer, new JsonSchemaResolver());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes this schema to a <see cref="JsonWriter"/> using the specified <see cref="JsonSchemaResolver"/>.
|
||||
/// </summary>
|
||||
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
|
||||
/// <param name="resolver">The resolver used.</param>
|
||||
public void WriteTo(JsonWriter writer, JsonSchemaResolver resolver)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(writer, "writer");
|
||||
ValidationUtils.ArgumentNotNull(resolver, "resolver");
|
||||
|
||||
JsonSchemaWriter schemaWriter = new JsonSchemaWriter(writer, resolver);
|
||||
schemaWriter.WriteSchema(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
|
||||
/// </returns>
|
||||
public override string ToString()
|
||||
{
|
||||
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
|
||||
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
|
||||
jsonWriter.Formatting = Formatting.Indented;
|
||||
|
||||
WriteTo(jsonWriter);
|
||||
|
||||
return writer.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,434 +1,434 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
using System.Globalization;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaBuilder
|
||||
{
|
||||
private JsonReader _reader;
|
||||
private readonly IList<JsonSchema> _stack;
|
||||
private readonly JsonSchemaResolver _resolver;
|
||||
private JsonSchema _currentSchema;
|
||||
|
||||
private void Push(JsonSchema value)
|
||||
{
|
||||
_currentSchema = value;
|
||||
_stack.Add(value);
|
||||
_resolver.LoadedSchemas.Add(value);
|
||||
}
|
||||
|
||||
private JsonSchema Pop()
|
||||
{
|
||||
JsonSchema poppedSchema = _currentSchema;
|
||||
_stack.RemoveAt(_stack.Count - 1);
|
||||
_currentSchema = _stack.LastOrDefault();
|
||||
|
||||
return poppedSchema;
|
||||
}
|
||||
|
||||
private JsonSchema CurrentSchema
|
||||
{
|
||||
get { return _currentSchema; }
|
||||
}
|
||||
|
||||
public JsonSchemaBuilder(JsonSchemaResolver resolver)
|
||||
{
|
||||
_stack = new List<JsonSchema>();
|
||||
_resolver = resolver;
|
||||
}
|
||||
|
||||
internal JsonSchema Parse(JsonReader reader)
|
||||
{
|
||||
_reader = reader;
|
||||
|
||||
if (reader.TokenType == JsonToken.None)
|
||||
_reader.Read();
|
||||
|
||||
return BuildSchema();
|
||||
}
|
||||
|
||||
private JsonSchema BuildSchema()
|
||||
{
|
||||
if (_reader.TokenType != JsonToken.StartObject)
|
||||
throw new Exception("Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
_reader.Read();
|
||||
// empty schema object
|
||||
if (_reader.TokenType == JsonToken.EndObject)
|
||||
{
|
||||
Push(new JsonSchema());
|
||||
return Pop();
|
||||
}
|
||||
|
||||
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
|
||||
_reader.Read();
|
||||
|
||||
// schema reference
|
||||
if (propertyName == JsonSchemaConstants.ReferencePropertyName)
|
||||
{
|
||||
string id = (string)_reader.Value;
|
||||
|
||||
// skip to the end of the current object
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
if (_reader.TokenType == JsonToken.StartObject)
|
||||
throw new Exception("Found StartObject within the schema reference with the Id '{0}'"
|
||||
.FormatWith(CultureInfo.InvariantCulture, id));
|
||||
}
|
||||
|
||||
JsonSchema referencedSchema = _resolver.GetSchema(id);
|
||||
if (referencedSchema == null)
|
||||
throw new Exception("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id));
|
||||
|
||||
return referencedSchema;
|
||||
}
|
||||
|
||||
// regular ol' schema object
|
||||
Push(new JsonSchema());
|
||||
|
||||
ProcessSchemaProperty(propertyName);
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
|
||||
_reader.Read();
|
||||
|
||||
ProcessSchemaProperty(propertyName);
|
||||
}
|
||||
|
||||
return Pop();
|
||||
}
|
||||
|
||||
private void ProcessSchemaProperty(string propertyName)
|
||||
{
|
||||
switch (propertyName)
|
||||
{
|
||||
case JsonSchemaConstants.TypePropertyName:
|
||||
CurrentSchema.Type = ProcessType();
|
||||
break;
|
||||
case JsonSchemaConstants.IdPropertyName:
|
||||
CurrentSchema.Id = (string) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.TitlePropertyName:
|
||||
CurrentSchema.Title = (string) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.DescriptionPropertyName:
|
||||
CurrentSchema.Description = (string)_reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.PropertiesPropertyName:
|
||||
ProcessProperties();
|
||||
break;
|
||||
case JsonSchemaConstants.ItemsPropertyName:
|
||||
ProcessItems();
|
||||
break;
|
||||
case JsonSchemaConstants.AdditionalPropertiesPropertyName:
|
||||
ProcessAdditionalProperties();
|
||||
break;
|
||||
case JsonSchemaConstants.PatternPropertiesPropertyName:
|
||||
ProcessPatternProperties();
|
||||
break;
|
||||
case JsonSchemaConstants.RequiredPropertyName:
|
||||
CurrentSchema.Required = (bool)_reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.RequiresPropertyName:
|
||||
CurrentSchema.Requires = (string) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.IdentityPropertyName:
|
||||
ProcessIdentity();
|
||||
break;
|
||||
case JsonSchemaConstants.MinimumPropertyName:
|
||||
CurrentSchema.Minimum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.MaximumPropertyName:
|
||||
CurrentSchema.Maximum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.ExclusiveMinimumPropertyName:
|
||||
CurrentSchema.ExclusiveMinimum = (bool)_reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.ExclusiveMaximumPropertyName:
|
||||
CurrentSchema.ExclusiveMaximum = (bool)_reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.MaximumLengthPropertyName:
|
||||
CurrentSchema.MaximumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.MinimumLengthPropertyName:
|
||||
CurrentSchema.MinimumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.MaximumItemsPropertyName:
|
||||
CurrentSchema.MaximumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.MinimumItemsPropertyName:
|
||||
CurrentSchema.MinimumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.DivisibleByPropertyName:
|
||||
CurrentSchema.DivisibleBy = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.DisallowPropertyName:
|
||||
CurrentSchema.Disallow = ProcessType();
|
||||
break;
|
||||
case JsonSchemaConstants.DefaultPropertyName:
|
||||
ProcessDefault();
|
||||
break;
|
||||
case JsonSchemaConstants.HiddenPropertyName:
|
||||
CurrentSchema.Hidden = (bool) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.ReadOnlyPropertyName:
|
||||
CurrentSchema.ReadOnly = (bool) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.FormatPropertyName:
|
||||
CurrentSchema.Format = (string) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.PatternPropertyName:
|
||||
CurrentSchema.Pattern = (string) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.OptionsPropertyName:
|
||||
ProcessOptions();
|
||||
break;
|
||||
case JsonSchemaConstants.EnumPropertyName:
|
||||
ProcessEnum();
|
||||
break;
|
||||
case JsonSchemaConstants.ExtendsPropertyName:
|
||||
ProcessExtends();
|
||||
break;
|
||||
default:
|
||||
_reader.Skip();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessExtends()
|
||||
{
|
||||
CurrentSchema.Extends = BuildSchema();
|
||||
}
|
||||
|
||||
private void ProcessEnum()
|
||||
{
|
||||
if (_reader.TokenType != JsonToken.StartArray)
|
||||
throw new Exception("Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
CurrentSchema.Enum = new List<JToken>();
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
JToken value = JToken.ReadFrom(_reader);
|
||||
CurrentSchema.Enum.Add(value);
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessOptions()
|
||||
{
|
||||
CurrentSchema.Options = new Dictionary<JToken, string>(new JTokenEqualityComparer());
|
||||
|
||||
switch (_reader.TokenType)
|
||||
{
|
||||
case JsonToken.StartArray:
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
if (_reader.TokenType != JsonToken.StartObject)
|
||||
throw new Exception("Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
string label = null;
|
||||
JToken value = null;
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
|
||||
_reader.Read();
|
||||
|
||||
switch (propertyName)
|
||||
{
|
||||
case JsonSchemaConstants.OptionValuePropertyName:
|
||||
value = JToken.ReadFrom(_reader);
|
||||
break;
|
||||
case JsonSchemaConstants.OptionLabelPropertyName:
|
||||
label = (string) _reader.Value;
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName));
|
||||
}
|
||||
}
|
||||
|
||||
if (value == null)
|
||||
throw new Exception("No value specified for JSON schema option.");
|
||||
|
||||
if (CurrentSchema.Options.ContainsKey(value))
|
||||
throw new Exception("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value));
|
||||
|
||||
CurrentSchema.Options.Add(value, label);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessDefault()
|
||||
{
|
||||
CurrentSchema.Default = JToken.ReadFrom(_reader);
|
||||
}
|
||||
|
||||
private void ProcessIdentity()
|
||||
{
|
||||
CurrentSchema.Identity = new List<string>();
|
||||
|
||||
switch (_reader.TokenType)
|
||||
{
|
||||
case JsonToken.String:
|
||||
CurrentSchema.Identity.Add(_reader.Value.ToString());
|
||||
break;
|
||||
case JsonToken.StartArray:
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
if (_reader.TokenType != JsonToken.String)
|
||||
throw new Exception("Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
CurrentSchema.Identity.Add(_reader.Value.ToString());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessAdditionalProperties()
|
||||
{
|
||||
if (_reader.TokenType == JsonToken.Boolean)
|
||||
CurrentSchema.AllowAdditionalProperties = (bool)_reader.Value;
|
||||
else
|
||||
CurrentSchema.AdditionalProperties = BuildSchema();
|
||||
}
|
||||
|
||||
private void ProcessPatternProperties()
|
||||
{
|
||||
Dictionary<string, JsonSchema> patternProperties = new Dictionary<string, JsonSchema>();
|
||||
|
||||
if (_reader.TokenType != JsonToken.StartObject)
|
||||
throw new Exception("Expected start object token.");
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
|
||||
_reader.Read();
|
||||
|
||||
if (patternProperties.ContainsKey(propertyName))
|
||||
throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
|
||||
|
||||
patternProperties.Add(propertyName, BuildSchema());
|
||||
}
|
||||
|
||||
CurrentSchema.PatternProperties = patternProperties;
|
||||
}
|
||||
|
||||
private void ProcessItems()
|
||||
{
|
||||
CurrentSchema.Items = new List<JsonSchema>();
|
||||
|
||||
switch (_reader.TokenType)
|
||||
{
|
||||
case JsonToken.StartObject:
|
||||
CurrentSchema.Items.Add(BuildSchema());
|
||||
break;
|
||||
case JsonToken.StartArray:
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
CurrentSchema.Items.Add(BuildSchema());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessProperties()
|
||||
{
|
||||
IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();
|
||||
|
||||
if (_reader.TokenType != JsonToken.StartObject)
|
||||
throw new Exception("Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
|
||||
_reader.Read();
|
||||
|
||||
if (properties.ContainsKey(propertyName))
|
||||
throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
|
||||
|
||||
properties.Add(propertyName, BuildSchema());
|
||||
}
|
||||
|
||||
CurrentSchema.Properties = properties;
|
||||
}
|
||||
|
||||
private JsonSchemaType? ProcessType()
|
||||
{
|
||||
switch (_reader.TokenType)
|
||||
{
|
||||
case JsonToken.String:
|
||||
return MapType(_reader.Value.ToString());
|
||||
case JsonToken.StartArray:
|
||||
// ensure type is in blank state before ORing values
|
||||
JsonSchemaType? type = JsonSchemaType.None;
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
if (_reader.TokenType != JsonToken.String)
|
||||
throw new Exception("Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
type = type | MapType(_reader.Value.ToString());
|
||||
}
|
||||
|
||||
return type;
|
||||
default:
|
||||
throw new Exception("Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
}
|
||||
}
|
||||
|
||||
internal static JsonSchemaType MapType(string type)
|
||||
{
|
||||
JsonSchemaType mappedType;
|
||||
if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType))
|
||||
throw new Exception("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type));
|
||||
|
||||
return mappedType;
|
||||
}
|
||||
|
||||
internal static string MapType(JsonSchemaType type)
|
||||
{
|
||||
return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key;
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
using System.Globalization;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaBuilder
|
||||
{
|
||||
private JsonReader _reader;
|
||||
private readonly IList<JsonSchema> _stack;
|
||||
private readonly JsonSchemaResolver _resolver;
|
||||
private JsonSchema _currentSchema;
|
||||
|
||||
private void Push(JsonSchema value)
|
||||
{
|
||||
_currentSchema = value;
|
||||
_stack.Add(value);
|
||||
_resolver.LoadedSchemas.Add(value);
|
||||
}
|
||||
|
||||
private JsonSchema Pop()
|
||||
{
|
||||
JsonSchema poppedSchema = _currentSchema;
|
||||
_stack.RemoveAt(_stack.Count - 1);
|
||||
_currentSchema = _stack.LastOrDefault();
|
||||
|
||||
return poppedSchema;
|
||||
}
|
||||
|
||||
private JsonSchema CurrentSchema
|
||||
{
|
||||
get { return _currentSchema; }
|
||||
}
|
||||
|
||||
public JsonSchemaBuilder(JsonSchemaResolver resolver)
|
||||
{
|
||||
_stack = new List<JsonSchema>();
|
||||
_resolver = resolver;
|
||||
}
|
||||
|
||||
internal JsonSchema Parse(JsonReader reader)
|
||||
{
|
||||
_reader = reader;
|
||||
|
||||
if (reader.TokenType == JsonToken.None)
|
||||
_reader.Read();
|
||||
|
||||
return BuildSchema();
|
||||
}
|
||||
|
||||
private JsonSchema BuildSchema()
|
||||
{
|
||||
if (_reader.TokenType != JsonToken.StartObject)
|
||||
throw new Exception("Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
_reader.Read();
|
||||
// empty schema object
|
||||
if (_reader.TokenType == JsonToken.EndObject)
|
||||
{
|
||||
Push(new JsonSchema());
|
||||
return Pop();
|
||||
}
|
||||
|
||||
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
|
||||
_reader.Read();
|
||||
|
||||
// schema reference
|
||||
if (propertyName == JsonSchemaConstants.ReferencePropertyName)
|
||||
{
|
||||
string id = (string)_reader.Value;
|
||||
|
||||
// skip to the end of the current object
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
if (_reader.TokenType == JsonToken.StartObject)
|
||||
throw new Exception("Found StartObject within the schema reference with the Id '{0}'"
|
||||
.FormatWith(CultureInfo.InvariantCulture, id));
|
||||
}
|
||||
|
||||
JsonSchema referencedSchema = _resolver.GetSchema(id);
|
||||
if (referencedSchema == null)
|
||||
throw new Exception("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id));
|
||||
|
||||
return referencedSchema;
|
||||
}
|
||||
|
||||
// regular ol' schema object
|
||||
Push(new JsonSchema());
|
||||
|
||||
ProcessSchemaProperty(propertyName);
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
|
||||
_reader.Read();
|
||||
|
||||
ProcessSchemaProperty(propertyName);
|
||||
}
|
||||
|
||||
return Pop();
|
||||
}
|
||||
|
||||
private void ProcessSchemaProperty(string propertyName)
|
||||
{
|
||||
switch (propertyName)
|
||||
{
|
||||
case JsonSchemaConstants.TypePropertyName:
|
||||
CurrentSchema.Type = ProcessType();
|
||||
break;
|
||||
case JsonSchemaConstants.IdPropertyName:
|
||||
CurrentSchema.Id = (string) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.TitlePropertyName:
|
||||
CurrentSchema.Title = (string) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.DescriptionPropertyName:
|
||||
CurrentSchema.Description = (string)_reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.PropertiesPropertyName:
|
||||
ProcessProperties();
|
||||
break;
|
||||
case JsonSchemaConstants.ItemsPropertyName:
|
||||
ProcessItems();
|
||||
break;
|
||||
case JsonSchemaConstants.AdditionalPropertiesPropertyName:
|
||||
ProcessAdditionalProperties();
|
||||
break;
|
||||
case JsonSchemaConstants.PatternPropertiesPropertyName:
|
||||
ProcessPatternProperties();
|
||||
break;
|
||||
case JsonSchemaConstants.RequiredPropertyName:
|
||||
CurrentSchema.Required = (bool)_reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.RequiresPropertyName:
|
||||
CurrentSchema.Requires = (string) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.IdentityPropertyName:
|
||||
ProcessIdentity();
|
||||
break;
|
||||
case JsonSchemaConstants.MinimumPropertyName:
|
||||
CurrentSchema.Minimum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.MaximumPropertyName:
|
||||
CurrentSchema.Maximum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.ExclusiveMinimumPropertyName:
|
||||
CurrentSchema.ExclusiveMinimum = (bool)_reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.ExclusiveMaximumPropertyName:
|
||||
CurrentSchema.ExclusiveMaximum = (bool)_reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.MaximumLengthPropertyName:
|
||||
CurrentSchema.MaximumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.MinimumLengthPropertyName:
|
||||
CurrentSchema.MinimumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.MaximumItemsPropertyName:
|
||||
CurrentSchema.MaximumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.MinimumItemsPropertyName:
|
||||
CurrentSchema.MinimumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.DivisibleByPropertyName:
|
||||
CurrentSchema.DivisibleBy = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
|
||||
break;
|
||||
case JsonSchemaConstants.DisallowPropertyName:
|
||||
CurrentSchema.Disallow = ProcessType();
|
||||
break;
|
||||
case JsonSchemaConstants.DefaultPropertyName:
|
||||
ProcessDefault();
|
||||
break;
|
||||
case JsonSchemaConstants.HiddenPropertyName:
|
||||
CurrentSchema.Hidden = (bool) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.ReadOnlyPropertyName:
|
||||
CurrentSchema.ReadOnly = (bool) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.FormatPropertyName:
|
||||
CurrentSchema.Format = (string) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.PatternPropertyName:
|
||||
CurrentSchema.Pattern = (string) _reader.Value;
|
||||
break;
|
||||
case JsonSchemaConstants.OptionsPropertyName:
|
||||
ProcessOptions();
|
||||
break;
|
||||
case JsonSchemaConstants.EnumPropertyName:
|
||||
ProcessEnum();
|
||||
break;
|
||||
case JsonSchemaConstants.ExtendsPropertyName:
|
||||
ProcessExtends();
|
||||
break;
|
||||
default:
|
||||
_reader.Skip();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessExtends()
|
||||
{
|
||||
CurrentSchema.Extends = BuildSchema();
|
||||
}
|
||||
|
||||
private void ProcessEnum()
|
||||
{
|
||||
if (_reader.TokenType != JsonToken.StartArray)
|
||||
throw new Exception("Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
CurrentSchema.Enum = new List<JToken>();
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
JToken value = JToken.ReadFrom(_reader);
|
||||
CurrentSchema.Enum.Add(value);
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessOptions()
|
||||
{
|
||||
CurrentSchema.Options = new Dictionary<JToken, string>(new JTokenEqualityComparer());
|
||||
|
||||
switch (_reader.TokenType)
|
||||
{
|
||||
case JsonToken.StartArray:
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
if (_reader.TokenType != JsonToken.StartObject)
|
||||
throw new Exception("Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
string label = null;
|
||||
JToken value = null;
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
|
||||
_reader.Read();
|
||||
|
||||
switch (propertyName)
|
||||
{
|
||||
case JsonSchemaConstants.OptionValuePropertyName:
|
||||
value = JToken.ReadFrom(_reader);
|
||||
break;
|
||||
case JsonSchemaConstants.OptionLabelPropertyName:
|
||||
label = (string) _reader.Value;
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName));
|
||||
}
|
||||
}
|
||||
|
||||
if (value == null)
|
||||
throw new Exception("No value specified for JSON schema option.");
|
||||
|
||||
if (CurrentSchema.Options.ContainsKey(value))
|
||||
throw new Exception("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value));
|
||||
|
||||
CurrentSchema.Options.Add(value, label);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessDefault()
|
||||
{
|
||||
CurrentSchema.Default = JToken.ReadFrom(_reader);
|
||||
}
|
||||
|
||||
private void ProcessIdentity()
|
||||
{
|
||||
CurrentSchema.Identity = new List<string>();
|
||||
|
||||
switch (_reader.TokenType)
|
||||
{
|
||||
case JsonToken.String:
|
||||
CurrentSchema.Identity.Add(_reader.Value.ToString());
|
||||
break;
|
||||
case JsonToken.StartArray:
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
if (_reader.TokenType != JsonToken.String)
|
||||
throw new Exception("Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
CurrentSchema.Identity.Add(_reader.Value.ToString());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessAdditionalProperties()
|
||||
{
|
||||
if (_reader.TokenType == JsonToken.Boolean)
|
||||
CurrentSchema.AllowAdditionalProperties = (bool)_reader.Value;
|
||||
else
|
||||
CurrentSchema.AdditionalProperties = BuildSchema();
|
||||
}
|
||||
|
||||
private void ProcessPatternProperties()
|
||||
{
|
||||
Dictionary<string, JsonSchema> patternProperties = new Dictionary<string, JsonSchema>();
|
||||
|
||||
if (_reader.TokenType != JsonToken.StartObject)
|
||||
throw new Exception("Expected start object token.");
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
|
||||
_reader.Read();
|
||||
|
||||
if (patternProperties.ContainsKey(propertyName))
|
||||
throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
|
||||
|
||||
patternProperties.Add(propertyName, BuildSchema());
|
||||
}
|
||||
|
||||
CurrentSchema.PatternProperties = patternProperties;
|
||||
}
|
||||
|
||||
private void ProcessItems()
|
||||
{
|
||||
CurrentSchema.Items = new List<JsonSchema>();
|
||||
|
||||
switch (_reader.TokenType)
|
||||
{
|
||||
case JsonToken.StartObject:
|
||||
CurrentSchema.Items.Add(BuildSchema());
|
||||
break;
|
||||
case JsonToken.StartArray:
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
CurrentSchema.Items.Add(BuildSchema());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessProperties()
|
||||
{
|
||||
IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();
|
||||
|
||||
if (_reader.TokenType != JsonToken.StartObject)
|
||||
throw new Exception("Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
|
||||
{
|
||||
string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
|
||||
_reader.Read();
|
||||
|
||||
if (properties.ContainsKey(propertyName))
|
||||
throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
|
||||
|
||||
properties.Add(propertyName, BuildSchema());
|
||||
}
|
||||
|
||||
CurrentSchema.Properties = properties;
|
||||
}
|
||||
|
||||
private JsonSchemaType? ProcessType()
|
||||
{
|
||||
switch (_reader.TokenType)
|
||||
{
|
||||
case JsonToken.String:
|
||||
return MapType(_reader.Value.ToString());
|
||||
case JsonToken.StartArray:
|
||||
// ensure type is in blank state before ORing values
|
||||
JsonSchemaType? type = JsonSchemaType.None;
|
||||
|
||||
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
|
||||
{
|
||||
if (_reader.TokenType != JsonToken.String)
|
||||
throw new Exception("Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
|
||||
type = type | MapType(_reader.Value.ToString());
|
||||
}
|
||||
|
||||
return type;
|
||||
default:
|
||||
throw new Exception("Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
|
||||
}
|
||||
}
|
||||
|
||||
internal static JsonSchemaType MapType(string type)
|
||||
{
|
||||
JsonSchemaType mappedType;
|
||||
if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType))
|
||||
throw new Exception("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type));
|
||||
|
||||
return mappedType;
|
||||
}
|
||||
|
||||
internal static string MapType(JsonSchemaType type)
|
||||
{
|
||||
return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,80 +1,80 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal static class JsonSchemaConstants
|
||||
{
|
||||
public const string TypePropertyName = "type";
|
||||
public const string PropertiesPropertyName = "properties";
|
||||
public const string ItemsPropertyName = "items";
|
||||
public const string RequiredPropertyName = "required";
|
||||
public const string PatternPropertiesPropertyName = "patternProperties";
|
||||
public const string AdditionalPropertiesPropertyName = "additionalProperties";
|
||||
public const string RequiresPropertyName = "requires";
|
||||
public const string IdentityPropertyName = "identity";
|
||||
public const string MinimumPropertyName = "minimum";
|
||||
public const string MaximumPropertyName = "maximum";
|
||||
public const string ExclusiveMinimumPropertyName = "exclusiveMinimum";
|
||||
public const string ExclusiveMaximumPropertyName = "exclusiveMaximum";
|
||||
public const string MinimumItemsPropertyName = "minItems";
|
||||
public const string MaximumItemsPropertyName = "maxItems";
|
||||
public const string PatternPropertyName = "pattern";
|
||||
public const string MaximumLengthPropertyName = "maxLength";
|
||||
public const string MinimumLengthPropertyName = "minLength";
|
||||
public const string EnumPropertyName = "enum";
|
||||
public const string OptionsPropertyName = "options";
|
||||
public const string ReadOnlyPropertyName = "readonly";
|
||||
public const string TitlePropertyName = "title";
|
||||
public const string DescriptionPropertyName = "description";
|
||||
public const string FormatPropertyName = "format";
|
||||
public const string DefaultPropertyName = "default";
|
||||
public const string TransientPropertyName = "transient";
|
||||
public const string DivisibleByPropertyName = "divisibleBy";
|
||||
public const string HiddenPropertyName = "hidden";
|
||||
public const string DisallowPropertyName = "disallow";
|
||||
public const string ExtendsPropertyName = "extends";
|
||||
public const string IdPropertyName = "id";
|
||||
|
||||
public const string OptionValuePropertyName = "value";
|
||||
public const string OptionLabelPropertyName = "label";
|
||||
|
||||
public const string ReferencePropertyName = "$ref";
|
||||
|
||||
public static readonly IDictionary<string, JsonSchemaType> JsonSchemaTypeMapping = new Dictionary<string, JsonSchemaType>
|
||||
{
|
||||
{"string", JsonSchemaType.String},
|
||||
{"object", JsonSchemaType.Object},
|
||||
{"integer", JsonSchemaType.Integer},
|
||||
{"number", JsonSchemaType.Float},
|
||||
{"null", JsonSchemaType.Null},
|
||||
{"boolean", JsonSchemaType.Boolean},
|
||||
{"array", JsonSchemaType.Array},
|
||||
{"any", JsonSchemaType.Any}
|
||||
};
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal static class JsonSchemaConstants
|
||||
{
|
||||
public const string TypePropertyName = "type";
|
||||
public const string PropertiesPropertyName = "properties";
|
||||
public const string ItemsPropertyName = "items";
|
||||
public const string RequiredPropertyName = "required";
|
||||
public const string PatternPropertiesPropertyName = "patternProperties";
|
||||
public const string AdditionalPropertiesPropertyName = "additionalProperties";
|
||||
public const string RequiresPropertyName = "requires";
|
||||
public const string IdentityPropertyName = "identity";
|
||||
public const string MinimumPropertyName = "minimum";
|
||||
public const string MaximumPropertyName = "maximum";
|
||||
public const string ExclusiveMinimumPropertyName = "exclusiveMinimum";
|
||||
public const string ExclusiveMaximumPropertyName = "exclusiveMaximum";
|
||||
public const string MinimumItemsPropertyName = "minItems";
|
||||
public const string MaximumItemsPropertyName = "maxItems";
|
||||
public const string PatternPropertyName = "pattern";
|
||||
public const string MaximumLengthPropertyName = "maxLength";
|
||||
public const string MinimumLengthPropertyName = "minLength";
|
||||
public const string EnumPropertyName = "enum";
|
||||
public const string OptionsPropertyName = "options";
|
||||
public const string ReadOnlyPropertyName = "readonly";
|
||||
public const string TitlePropertyName = "title";
|
||||
public const string DescriptionPropertyName = "description";
|
||||
public const string FormatPropertyName = "format";
|
||||
public const string DefaultPropertyName = "default";
|
||||
public const string TransientPropertyName = "transient";
|
||||
public const string DivisibleByPropertyName = "divisibleBy";
|
||||
public const string HiddenPropertyName = "hidden";
|
||||
public const string DisallowPropertyName = "disallow";
|
||||
public const string ExtendsPropertyName = "extends";
|
||||
public const string IdPropertyName = "id";
|
||||
|
||||
public const string OptionValuePropertyName = "value";
|
||||
public const string OptionLabelPropertyName = "label";
|
||||
|
||||
public const string ReferencePropertyName = "$ref";
|
||||
|
||||
public static readonly IDictionary<string, JsonSchemaType> JsonSchemaTypeMapping = new Dictionary<string, JsonSchemaType>
|
||||
{
|
||||
{"string", JsonSchemaType.String},
|
||||
{"object", JsonSchemaType.Object},
|
||||
{"integer", JsonSchemaType.Integer},
|
||||
{"number", JsonSchemaType.Float},
|
||||
{"null", JsonSchemaType.Null},
|
||||
{"boolean", JsonSchemaType.Boolean},
|
||||
{"array", JsonSchemaType.Array},
|
||||
{"any", JsonSchemaType.Any}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,108 +1,108 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns detailed information about the schema exception.
|
||||
/// </summary>
|
||||
#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE)
|
||||
[Serializable]
|
||||
#endif
|
||||
public class JsonSchemaException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the line number indicating where the error occurred.
|
||||
/// </summary>
|
||||
/// <value>The line number indicating where the error occurred.</value>
|
||||
public int LineNumber { get; private set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets the line position indicating where the error occurred.
|
||||
/// </summary>
|
||||
/// <value>The line position indicating where the error occurred.</value>
|
||||
public int LinePosition { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path to the JSON where the error occurred.
|
||||
/// </summary>
|
||||
/// <value>The path to the JSON where the error occurred.</value>
|
||||
public string Path { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class.
|
||||
/// </summary>
|
||||
public JsonSchemaException()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class
|
||||
/// with a specified error message.
|
||||
/// </summary>
|
||||
/// <param name="message">The error message that explains the reason for the exception.</param>
|
||||
public JsonSchemaException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class
|
||||
/// with a specified error message and a reference to the inner exception that is the cause of this exception.
|
||||
/// </summary>
|
||||
/// <param name="message">The error message that explains the reason for the exception.</param>
|
||||
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
|
||||
public JsonSchemaException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE)
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
|
||||
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
|
||||
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is null. </exception>
|
||||
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). </exception>
|
||||
public JsonSchemaException(SerializationInfo info, StreamingContext context)
|
||||
: base(info, context)
|
||||
{
|
||||
}
|
||||
#endif
|
||||
|
||||
internal JsonSchemaException(string message, Exception innerException, string path, int lineNumber, int linePosition)
|
||||
: base(message, innerException)
|
||||
{
|
||||
Path = path;
|
||||
LineNumber = lineNumber;
|
||||
LinePosition = linePosition;
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns detailed information about the schema exception.
|
||||
/// </summary>
|
||||
#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE)
|
||||
[Serializable]
|
||||
#endif
|
||||
public class JsonSchemaException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the line number indicating where the error occurred.
|
||||
/// </summary>
|
||||
/// <value>The line number indicating where the error occurred.</value>
|
||||
public int LineNumber { get; private set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets the line position indicating where the error occurred.
|
||||
/// </summary>
|
||||
/// <value>The line position indicating where the error occurred.</value>
|
||||
public int LinePosition { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path to the JSON where the error occurred.
|
||||
/// </summary>
|
||||
/// <value>The path to the JSON where the error occurred.</value>
|
||||
public string Path { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class.
|
||||
/// </summary>
|
||||
public JsonSchemaException()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class
|
||||
/// with a specified error message.
|
||||
/// </summary>
|
||||
/// <param name="message">The error message that explains the reason for the exception.</param>
|
||||
public JsonSchemaException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class
|
||||
/// with a specified error message and a reference to the inner exception that is the cause of this exception.
|
||||
/// </summary>
|
||||
/// <param name="message">The error message that explains the reason for the exception.</param>
|
||||
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
|
||||
public JsonSchemaException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE)
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchemaException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
|
||||
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
|
||||
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is null. </exception>
|
||||
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). </exception>
|
||||
public JsonSchemaException(SerializationInfo info, StreamingContext context)
|
||||
: base(info, context)
|
||||
{
|
||||
}
|
||||
#endif
|
||||
|
||||
internal JsonSchemaException(string message, Exception innerException, string path, int lineNumber, int linePosition)
|
||||
: base(message, innerException)
|
||||
{
|
||||
Path = path;
|
||||
LineNumber = lineNumber;
|
||||
LinePosition = linePosition;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,464 +1,464 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.ComponentModel;
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
#if NETFX_CORE
|
||||
using IConvertible = Newtonsoft.Json.Utilities.Convertible;
|
||||
#endif
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
|
||||
/// </summary>
|
||||
public class JsonSchemaGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets how undefined schemas are handled by the serializer.
|
||||
/// </summary>
|
||||
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
|
||||
|
||||
private IContractResolver _contractResolver;
|
||||
/// <summary>
|
||||
/// Gets or sets the contract resolver.
|
||||
/// </summary>
|
||||
/// <value>The contract resolver.</value>
|
||||
public IContractResolver ContractResolver
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_contractResolver == null)
|
||||
return DefaultContractResolver.Instance;
|
||||
|
||||
return _contractResolver;
|
||||
}
|
||||
set { _contractResolver = value; }
|
||||
}
|
||||
|
||||
private class TypeSchema
|
||||
{
|
||||
public Type Type { get; private set; }
|
||||
public JsonSchema Schema { get; private set;}
|
||||
|
||||
public TypeSchema(Type type, JsonSchema schema)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(type, "type");
|
||||
ValidationUtils.ArgumentNotNull(schema, "schema");
|
||||
|
||||
Type = type;
|
||||
Schema = schema;
|
||||
}
|
||||
}
|
||||
|
||||
private JsonSchemaResolver _resolver;
|
||||
private readonly IList<TypeSchema> _stack = new List<TypeSchema>();
|
||||
private JsonSchema _currentSchema;
|
||||
|
||||
private JsonSchema CurrentSchema
|
||||
{
|
||||
get { return _currentSchema; }
|
||||
}
|
||||
|
||||
private void Push(TypeSchema typeSchema)
|
||||
{
|
||||
_currentSchema = typeSchema.Schema;
|
||||
_stack.Add(typeSchema);
|
||||
_resolver.LoadedSchemas.Add(typeSchema.Schema);
|
||||
}
|
||||
|
||||
private TypeSchema Pop()
|
||||
{
|
||||
TypeSchema popped = _stack[_stack.Count - 1];
|
||||
_stack.RemoveAt(_stack.Count - 1);
|
||||
TypeSchema newValue = _stack.LastOrDefault();
|
||||
if (newValue != null)
|
||||
{
|
||||
_currentSchema = newValue.Schema;
|
||||
}
|
||||
else
|
||||
{
|
||||
_currentSchema = null;
|
||||
}
|
||||
|
||||
return popped;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a <see cref="JsonSchema"/> from the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
|
||||
public JsonSchema Generate(Type type)
|
||||
{
|
||||
return Generate(type, new JsonSchemaResolver(), false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a <see cref="JsonSchema"/> from the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
|
||||
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
|
||||
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
|
||||
{
|
||||
return Generate(type, resolver, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a <see cref="JsonSchema"/> from the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
|
||||
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
|
||||
public JsonSchema Generate(Type type, bool rootSchemaNullable)
|
||||
{
|
||||
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a <see cref="JsonSchema"/> from the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
|
||||
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
|
||||
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
|
||||
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(type, "type");
|
||||
ValidationUtils.ArgumentNotNull(resolver, "resolver");
|
||||
|
||||
_resolver = resolver;
|
||||
|
||||
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
|
||||
}
|
||||
|
||||
private string GetTitle(Type type)
|
||||
{
|
||||
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
|
||||
|
||||
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
|
||||
return containerAttribute.Title;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private string GetDescription(Type type)
|
||||
{
|
||||
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
|
||||
|
||||
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
|
||||
return containerAttribute.Description;
|
||||
|
||||
#if !PocketPC && !NETFX_CORE
|
||||
DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type);
|
||||
if (descriptionAttribute != null)
|
||||
return descriptionAttribute.Description;
|
||||
#endif
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private string GetTypeId(Type type, bool explicitOnly)
|
||||
{
|
||||
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
|
||||
|
||||
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
|
||||
return containerAttribute.Id;
|
||||
|
||||
if (explicitOnly)
|
||||
return null;
|
||||
|
||||
switch (UndefinedSchemaIdHandling)
|
||||
{
|
||||
case UndefinedSchemaIdHandling.UseTypeName:
|
||||
return type.FullName;
|
||||
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
|
||||
return type.AssemblyQualifiedName;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(type, "type");
|
||||
|
||||
string resolvedId = GetTypeId(type, false);
|
||||
string explicitId = GetTypeId(type, true);
|
||||
|
||||
if (!string.IsNullOrEmpty(resolvedId))
|
||||
{
|
||||
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
|
||||
if (resolvedSchema != null)
|
||||
{
|
||||
// resolved schema is not null but referencing member allows nulls
|
||||
// change resolved schema to allow nulls. hacky but what are ya gonna do?
|
||||
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
|
||||
resolvedSchema.Type |= JsonSchemaType.Null;
|
||||
if (required && resolvedSchema.Required != true)
|
||||
resolvedSchema.Required = true;
|
||||
|
||||
return resolvedSchema;
|
||||
}
|
||||
}
|
||||
|
||||
// test for unresolved circular reference
|
||||
if (_stack.Any(tc => tc.Type == type))
|
||||
{
|
||||
throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
|
||||
}
|
||||
|
||||
JsonContract contract = ContractResolver.ResolveContract(type);
|
||||
JsonConverter converter;
|
||||
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
|
||||
{
|
||||
JsonSchema converterSchema = converter.GetSchema();
|
||||
if (converterSchema != null)
|
||||
return converterSchema;
|
||||
}
|
||||
|
||||
Push(new TypeSchema(type, new JsonSchema()));
|
||||
|
||||
if (explicitId != null)
|
||||
CurrentSchema.Id = explicitId;
|
||||
|
||||
if (required)
|
||||
CurrentSchema.Required = true;
|
||||
CurrentSchema.Title = GetTitle(type);
|
||||
CurrentSchema.Description = GetDescription(type);
|
||||
|
||||
if (converter != null)
|
||||
{
|
||||
// todo: Add GetSchema to JsonConverter and use here?
|
||||
CurrentSchema.Type = JsonSchemaType.Any;
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (contract.ContractType)
|
||||
{
|
||||
case JsonContractType.Object:
|
||||
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
|
||||
CurrentSchema.Id = GetTypeId(type, false);
|
||||
GenerateObjectSchema(type, (JsonObjectContract) contract);
|
||||
break;
|
||||
case JsonContractType.Array:
|
||||
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
|
||||
|
||||
CurrentSchema.Id = GetTypeId(type, false);
|
||||
|
||||
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
|
||||
bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);
|
||||
|
||||
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
|
||||
if (collectionItemType != null)
|
||||
{
|
||||
CurrentSchema.Items = new List<JsonSchema>();
|
||||
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
|
||||
}
|
||||
break;
|
||||
case JsonContractType.Primitive:
|
||||
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
|
||||
|
||||
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof (FlagsAttribute), true))
|
||||
{
|
||||
CurrentSchema.Enum = new List<JToken>();
|
||||
CurrentSchema.Options = new Dictionary<JToken, string>();
|
||||
|
||||
EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type);
|
||||
foreach (EnumValue<long> enumValue in enumValues)
|
||||
{
|
||||
JToken value = JToken.FromObject(enumValue.Value);
|
||||
|
||||
CurrentSchema.Enum.Add(value);
|
||||
CurrentSchema.Options.Add(value, enumValue.Name);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case JsonContractType.String:
|
||||
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
|
||||
? JsonSchemaType.String
|
||||
: AddNullType(JsonSchemaType.String, valueRequired);
|
||||
|
||||
CurrentSchema.Type = schemaType;
|
||||
break;
|
||||
case JsonContractType.Dictionary:
|
||||
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
|
||||
|
||||
Type keyType;
|
||||
Type valueType;
|
||||
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
|
||||
|
||||
if (keyType != null)
|
||||
{
|
||||
// can be converted to a string
|
||||
if (ConvertUtils.IsConvertible(keyType))
|
||||
{
|
||||
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
|
||||
}
|
||||
}
|
||||
break;
|
||||
#if !SILVERLIGHT && !PocketPC && !NETFX_CORE
|
||||
case JsonContractType.Serializable:
|
||||
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
|
||||
CurrentSchema.Id = GetTypeId(type, false);
|
||||
GenerateISerializableContract(type, (JsonISerializableContract) contract);
|
||||
break;
|
||||
#endif
|
||||
#if !(NET35 || NET20 || WINDOWS_PHONE)
|
||||
case JsonContractType.Dynamic:
|
||||
#endif
|
||||
case JsonContractType.Linq:
|
||||
CurrentSchema.Type = JsonSchemaType.Any;
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
|
||||
}
|
||||
}
|
||||
|
||||
return Pop().Schema;
|
||||
}
|
||||
|
||||
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired)
|
||||
{
|
||||
if (valueRequired != Required.Always)
|
||||
return type | JsonSchemaType.Null;
|
||||
|
||||
return type;
|
||||
}
|
||||
|
||||
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
|
||||
{
|
||||
return ((value & flag) == flag);
|
||||
}
|
||||
|
||||
private void GenerateObjectSchema(Type type, JsonObjectContract contract)
|
||||
{
|
||||
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
|
||||
foreach (JsonProperty property in contract.Properties)
|
||||
{
|
||||
if (!property.Ignored)
|
||||
{
|
||||
bool optional = property.NullValueHandling == NullValueHandling.Ignore ||
|
||||
HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) ||
|
||||
property.ShouldSerialize != null ||
|
||||
property.GetIsSpecified != null;
|
||||
|
||||
JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional);
|
||||
|
||||
if (property.DefaultValue != null)
|
||||
propertySchema.Default = JToken.FromObject(property.DefaultValue);
|
||||
|
||||
CurrentSchema.Properties.Add(property.PropertyName, propertySchema);
|
||||
}
|
||||
}
|
||||
|
||||
if (type.IsSealed())
|
||||
CurrentSchema.AllowAdditionalProperties = false;
|
||||
}
|
||||
|
||||
#if !SILVERLIGHT && !PocketPC && !NETFX_CORE
|
||||
private void GenerateISerializableContract(Type type, JsonISerializableContract contract)
|
||||
{
|
||||
CurrentSchema.AllowAdditionalProperties = true;
|
||||
}
|
||||
#endif
|
||||
|
||||
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
|
||||
{
|
||||
// default value is Any
|
||||
if (value == null)
|
||||
return true;
|
||||
|
||||
bool match = ((value & flag) == flag);
|
||||
if (match)
|
||||
return true;
|
||||
|
||||
// integer is a subset of float
|
||||
if (value == JsonSchemaType.Float && flag == JsonSchemaType.Integer)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
|
||||
{
|
||||
JsonSchemaType schemaType = JsonSchemaType.None;
|
||||
if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
|
||||
{
|
||||
schemaType = JsonSchemaType.Null;
|
||||
if (ReflectionUtils.IsNullableType(type))
|
||||
type = Nullable.GetUnderlyingType(type);
|
||||
}
|
||||
|
||||
TypeCode typeCode = ConvertUtils.GetTypeCode(type);
|
||||
|
||||
switch (typeCode)
|
||||
{
|
||||
case TypeCode.Empty:
|
||||
case TypeCode.Object:
|
||||
return schemaType | JsonSchemaType.String;
|
||||
#if !NETFX_CORE
|
||||
case TypeCode.DBNull:
|
||||
return schemaType | JsonSchemaType.Null;
|
||||
#endif
|
||||
case TypeCode.Boolean:
|
||||
return schemaType | JsonSchemaType.Boolean;
|
||||
case TypeCode.Char:
|
||||
return schemaType | JsonSchemaType.String;
|
||||
case TypeCode.SByte:
|
||||
case TypeCode.Byte:
|
||||
case TypeCode.Int16:
|
||||
case TypeCode.UInt16:
|
||||
case TypeCode.Int32:
|
||||
case TypeCode.UInt32:
|
||||
case TypeCode.Int64:
|
||||
case TypeCode.UInt64:
|
||||
return schemaType | JsonSchemaType.Integer;
|
||||
case TypeCode.Single:
|
||||
case TypeCode.Double:
|
||||
case TypeCode.Decimal:
|
||||
return schemaType | JsonSchemaType.Float;
|
||||
// convert to string?
|
||||
case TypeCode.DateTime:
|
||||
return schemaType | JsonSchemaType.String;
|
||||
case TypeCode.String:
|
||||
return schemaType | JsonSchemaType.String;
|
||||
default:
|
||||
throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.ComponentModel;
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
#if NETFX_CORE
|
||||
using IConvertible = Newtonsoft.Json.Utilities.Convertible;
|
||||
#endif
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
|
||||
/// </summary>
|
||||
public class JsonSchemaGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets how undefined schemas are handled by the serializer.
|
||||
/// </summary>
|
||||
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
|
||||
|
||||
private IContractResolver _contractResolver;
|
||||
/// <summary>
|
||||
/// Gets or sets the contract resolver.
|
||||
/// </summary>
|
||||
/// <value>The contract resolver.</value>
|
||||
public IContractResolver ContractResolver
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_contractResolver == null)
|
||||
return DefaultContractResolver.Instance;
|
||||
|
||||
return _contractResolver;
|
||||
}
|
||||
set { _contractResolver = value; }
|
||||
}
|
||||
|
||||
private class TypeSchema
|
||||
{
|
||||
public Type Type { get; private set; }
|
||||
public JsonSchema Schema { get; private set;}
|
||||
|
||||
public TypeSchema(Type type, JsonSchema schema)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(type, "type");
|
||||
ValidationUtils.ArgumentNotNull(schema, "schema");
|
||||
|
||||
Type = type;
|
||||
Schema = schema;
|
||||
}
|
||||
}
|
||||
|
||||
private JsonSchemaResolver _resolver;
|
||||
private readonly IList<TypeSchema> _stack = new List<TypeSchema>();
|
||||
private JsonSchema _currentSchema;
|
||||
|
||||
private JsonSchema CurrentSchema
|
||||
{
|
||||
get { return _currentSchema; }
|
||||
}
|
||||
|
||||
private void Push(TypeSchema typeSchema)
|
||||
{
|
||||
_currentSchema = typeSchema.Schema;
|
||||
_stack.Add(typeSchema);
|
||||
_resolver.LoadedSchemas.Add(typeSchema.Schema);
|
||||
}
|
||||
|
||||
private TypeSchema Pop()
|
||||
{
|
||||
TypeSchema popped = _stack[_stack.Count - 1];
|
||||
_stack.RemoveAt(_stack.Count - 1);
|
||||
TypeSchema newValue = _stack.LastOrDefault();
|
||||
if (newValue != null)
|
||||
{
|
||||
_currentSchema = newValue.Schema;
|
||||
}
|
||||
else
|
||||
{
|
||||
_currentSchema = null;
|
||||
}
|
||||
|
||||
return popped;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a <see cref="JsonSchema"/> from the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
|
||||
public JsonSchema Generate(Type type)
|
||||
{
|
||||
return Generate(type, new JsonSchemaResolver(), false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a <see cref="JsonSchema"/> from the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
|
||||
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
|
||||
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
|
||||
{
|
||||
return Generate(type, resolver, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a <see cref="JsonSchema"/> from the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
|
||||
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
|
||||
public JsonSchema Generate(Type type, bool rootSchemaNullable)
|
||||
{
|
||||
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a <see cref="JsonSchema"/> from the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
|
||||
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
|
||||
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
|
||||
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(type, "type");
|
||||
ValidationUtils.ArgumentNotNull(resolver, "resolver");
|
||||
|
||||
_resolver = resolver;
|
||||
|
||||
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
|
||||
}
|
||||
|
||||
private string GetTitle(Type type)
|
||||
{
|
||||
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
|
||||
|
||||
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
|
||||
return containerAttribute.Title;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private string GetDescription(Type type)
|
||||
{
|
||||
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
|
||||
|
||||
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
|
||||
return containerAttribute.Description;
|
||||
|
||||
#if !PocketPC && !NETFX_CORE
|
||||
DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type);
|
||||
if (descriptionAttribute != null)
|
||||
return descriptionAttribute.Description;
|
||||
#endif
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private string GetTypeId(Type type, bool explicitOnly)
|
||||
{
|
||||
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
|
||||
|
||||
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
|
||||
return containerAttribute.Id;
|
||||
|
||||
if (explicitOnly)
|
||||
return null;
|
||||
|
||||
switch (UndefinedSchemaIdHandling)
|
||||
{
|
||||
case UndefinedSchemaIdHandling.UseTypeName:
|
||||
return type.FullName;
|
||||
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
|
||||
return type.AssemblyQualifiedName;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(type, "type");
|
||||
|
||||
string resolvedId = GetTypeId(type, false);
|
||||
string explicitId = GetTypeId(type, true);
|
||||
|
||||
if (!string.IsNullOrEmpty(resolvedId))
|
||||
{
|
||||
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
|
||||
if (resolvedSchema != null)
|
||||
{
|
||||
// resolved schema is not null but referencing member allows nulls
|
||||
// change resolved schema to allow nulls. hacky but what are ya gonna do?
|
||||
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
|
||||
resolvedSchema.Type |= JsonSchemaType.Null;
|
||||
if (required && resolvedSchema.Required != true)
|
||||
resolvedSchema.Required = true;
|
||||
|
||||
return resolvedSchema;
|
||||
}
|
||||
}
|
||||
|
||||
// test for unresolved circular reference
|
||||
if (_stack.Any(tc => tc.Type == type))
|
||||
{
|
||||
throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
|
||||
}
|
||||
|
||||
JsonContract contract = ContractResolver.ResolveContract(type);
|
||||
JsonConverter converter;
|
||||
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
|
||||
{
|
||||
JsonSchema converterSchema = converter.GetSchema();
|
||||
if (converterSchema != null)
|
||||
return converterSchema;
|
||||
}
|
||||
|
||||
Push(new TypeSchema(type, new JsonSchema()));
|
||||
|
||||
if (explicitId != null)
|
||||
CurrentSchema.Id = explicitId;
|
||||
|
||||
if (required)
|
||||
CurrentSchema.Required = true;
|
||||
CurrentSchema.Title = GetTitle(type);
|
||||
CurrentSchema.Description = GetDescription(type);
|
||||
|
||||
if (converter != null)
|
||||
{
|
||||
// todo: Add GetSchema to JsonConverter and use here?
|
||||
CurrentSchema.Type = JsonSchemaType.Any;
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (contract.ContractType)
|
||||
{
|
||||
case JsonContractType.Object:
|
||||
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
|
||||
CurrentSchema.Id = GetTypeId(type, false);
|
||||
GenerateObjectSchema(type, (JsonObjectContract) contract);
|
||||
break;
|
||||
case JsonContractType.Array:
|
||||
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
|
||||
|
||||
CurrentSchema.Id = GetTypeId(type, false);
|
||||
|
||||
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
|
||||
bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);
|
||||
|
||||
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
|
||||
if (collectionItemType != null)
|
||||
{
|
||||
CurrentSchema.Items = new List<JsonSchema>();
|
||||
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
|
||||
}
|
||||
break;
|
||||
case JsonContractType.Primitive:
|
||||
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
|
||||
|
||||
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof (FlagsAttribute), true))
|
||||
{
|
||||
CurrentSchema.Enum = new List<JToken>();
|
||||
CurrentSchema.Options = new Dictionary<JToken, string>();
|
||||
|
||||
EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type);
|
||||
foreach (EnumValue<long> enumValue in enumValues)
|
||||
{
|
||||
JToken value = JToken.FromObject(enumValue.Value);
|
||||
|
||||
CurrentSchema.Enum.Add(value);
|
||||
CurrentSchema.Options.Add(value, enumValue.Name);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case JsonContractType.String:
|
||||
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
|
||||
? JsonSchemaType.String
|
||||
: AddNullType(JsonSchemaType.String, valueRequired);
|
||||
|
||||
CurrentSchema.Type = schemaType;
|
||||
break;
|
||||
case JsonContractType.Dictionary:
|
||||
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
|
||||
|
||||
Type keyType;
|
||||
Type valueType;
|
||||
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
|
||||
|
||||
if (keyType != null)
|
||||
{
|
||||
// can be converted to a string
|
||||
if (ConvertUtils.IsConvertible(keyType))
|
||||
{
|
||||
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
|
||||
}
|
||||
}
|
||||
break;
|
||||
#if !SILVERLIGHT && !PocketPC && !NETFX_CORE
|
||||
case JsonContractType.Serializable:
|
||||
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
|
||||
CurrentSchema.Id = GetTypeId(type, false);
|
||||
GenerateISerializableContract(type, (JsonISerializableContract) contract);
|
||||
break;
|
||||
#endif
|
||||
#if !(NET35 || NET20 || WINDOWS_PHONE)
|
||||
case JsonContractType.Dynamic:
|
||||
#endif
|
||||
case JsonContractType.Linq:
|
||||
CurrentSchema.Type = JsonSchemaType.Any;
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
|
||||
}
|
||||
}
|
||||
|
||||
return Pop().Schema;
|
||||
}
|
||||
|
||||
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired)
|
||||
{
|
||||
if (valueRequired != Required.Always)
|
||||
return type | JsonSchemaType.Null;
|
||||
|
||||
return type;
|
||||
}
|
||||
|
||||
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
|
||||
{
|
||||
return ((value & flag) == flag);
|
||||
}
|
||||
|
||||
private void GenerateObjectSchema(Type type, JsonObjectContract contract)
|
||||
{
|
||||
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
|
||||
foreach (JsonProperty property in contract.Properties)
|
||||
{
|
||||
if (!property.Ignored)
|
||||
{
|
||||
bool optional = property.NullValueHandling == NullValueHandling.Ignore ||
|
||||
HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) ||
|
||||
property.ShouldSerialize != null ||
|
||||
property.GetIsSpecified != null;
|
||||
|
||||
JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional);
|
||||
|
||||
if (property.DefaultValue != null)
|
||||
propertySchema.Default = JToken.FromObject(property.DefaultValue);
|
||||
|
||||
CurrentSchema.Properties.Add(property.PropertyName, propertySchema);
|
||||
}
|
||||
}
|
||||
|
||||
if (type.IsSealed())
|
||||
CurrentSchema.AllowAdditionalProperties = false;
|
||||
}
|
||||
|
||||
#if !SILVERLIGHT && !PocketPC && !NETFX_CORE
|
||||
private void GenerateISerializableContract(Type type, JsonISerializableContract contract)
|
||||
{
|
||||
CurrentSchema.AllowAdditionalProperties = true;
|
||||
}
|
||||
#endif
|
||||
|
||||
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
|
||||
{
|
||||
// default value is Any
|
||||
if (value == null)
|
||||
return true;
|
||||
|
||||
bool match = ((value & flag) == flag);
|
||||
if (match)
|
||||
return true;
|
||||
|
||||
// integer is a subset of float
|
||||
if (value == JsonSchemaType.Float && flag == JsonSchemaType.Integer)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
|
||||
{
|
||||
JsonSchemaType schemaType = JsonSchemaType.None;
|
||||
if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
|
||||
{
|
||||
schemaType = JsonSchemaType.Null;
|
||||
if (ReflectionUtils.IsNullableType(type))
|
||||
type = Nullable.GetUnderlyingType(type);
|
||||
}
|
||||
|
||||
TypeCode typeCode = ConvertUtils.GetTypeCode(type);
|
||||
|
||||
switch (typeCode)
|
||||
{
|
||||
case TypeCode.Empty:
|
||||
case TypeCode.Object:
|
||||
return schemaType | JsonSchemaType.String;
|
||||
#if !NETFX_CORE
|
||||
case TypeCode.DBNull:
|
||||
return schemaType | JsonSchemaType.Null;
|
||||
#endif
|
||||
case TypeCode.Boolean:
|
||||
return schemaType | JsonSchemaType.Boolean;
|
||||
case TypeCode.Char:
|
||||
return schemaType | JsonSchemaType.String;
|
||||
case TypeCode.SByte:
|
||||
case TypeCode.Byte:
|
||||
case TypeCode.Int16:
|
||||
case TypeCode.UInt16:
|
||||
case TypeCode.Int32:
|
||||
case TypeCode.UInt32:
|
||||
case TypeCode.Int64:
|
||||
case TypeCode.UInt64:
|
||||
return schemaType | JsonSchemaType.Integer;
|
||||
case TypeCode.Single:
|
||||
case TypeCode.Double:
|
||||
case TypeCode.Decimal:
|
||||
return schemaType | JsonSchemaType.Float;
|
||||
// convert to string?
|
||||
case TypeCode.DateTime:
|
||||
return schemaType | JsonSchemaType.String;
|
||||
case TypeCode.String:
|
||||
return schemaType | JsonSchemaType.String;
|
||||
default:
|
||||
throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,111 +1,111 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaModel
|
||||
{
|
||||
public bool Required { get; set; }
|
||||
public JsonSchemaType Type { get; set; }
|
||||
public int? MinimumLength { get; set; }
|
||||
public int? MaximumLength { get; set; }
|
||||
public double? DivisibleBy { get; set; }
|
||||
public double? Minimum { get; set; }
|
||||
public double? Maximum { get; set; }
|
||||
public bool ExclusiveMinimum { get; set; }
|
||||
public bool ExclusiveMaximum { get; set; }
|
||||
public int? MinimumItems { get; set; }
|
||||
public int? MaximumItems { get; set; }
|
||||
public IList<string> Patterns { get; set; }
|
||||
public IList<JsonSchemaModel> Items { get; set; }
|
||||
public IDictionary<string, JsonSchemaModel> Properties { get; set; }
|
||||
public IDictionary<string, JsonSchemaModel> PatternProperties { get; set; }
|
||||
public JsonSchemaModel AdditionalProperties { get; set; }
|
||||
public bool AllowAdditionalProperties { get; set; }
|
||||
public IList<JToken> Enum { get; set; }
|
||||
public JsonSchemaType Disallow { get; set; }
|
||||
|
||||
public JsonSchemaModel()
|
||||
{
|
||||
Type = JsonSchemaType.Any;
|
||||
AllowAdditionalProperties = true;
|
||||
Required = false;
|
||||
}
|
||||
|
||||
public static JsonSchemaModel Create(IList<JsonSchema> schemata)
|
||||
{
|
||||
JsonSchemaModel model = new JsonSchemaModel();
|
||||
|
||||
foreach (JsonSchema schema in schemata)
|
||||
{
|
||||
Combine(model, schema);
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
private static void Combine(JsonSchemaModel model, JsonSchema schema)
|
||||
{
|
||||
// Version 3 of the Draft JSON Schema has the default value of Not Required
|
||||
model.Required = model.Required || (schema.Required ?? false);
|
||||
model.Type = model.Type & (schema.Type ?? JsonSchemaType.Any);
|
||||
|
||||
model.MinimumLength = MathUtils.Max(model.MinimumLength, schema.MinimumLength);
|
||||
model.MaximumLength = MathUtils.Min(model.MaximumLength, schema.MaximumLength);
|
||||
|
||||
// not sure what is the best way to combine divisibleBy
|
||||
model.DivisibleBy = MathUtils.Max(model.DivisibleBy, schema.DivisibleBy);
|
||||
|
||||
model.Minimum = MathUtils.Max(model.Minimum, schema.Minimum);
|
||||
model.Maximum = MathUtils.Max(model.Maximum, schema.Maximum);
|
||||
model.ExclusiveMinimum = model.ExclusiveMinimum || (schema.ExclusiveMinimum ?? false);
|
||||
model.ExclusiveMaximum = model.ExclusiveMaximum || (schema.ExclusiveMaximum ?? false);
|
||||
|
||||
model.MinimumItems = MathUtils.Max(model.MinimumItems, schema.MinimumItems);
|
||||
model.MaximumItems = MathUtils.Min(model.MaximumItems, schema.MaximumItems);
|
||||
model.AllowAdditionalProperties = model.AllowAdditionalProperties && schema.AllowAdditionalProperties;
|
||||
if (schema.Enum != null)
|
||||
{
|
||||
if (model.Enum == null)
|
||||
model.Enum = new List<JToken>();
|
||||
|
||||
model.Enum.AddRangeDistinct(schema.Enum, new JTokenEqualityComparer());
|
||||
}
|
||||
model.Disallow = model.Disallow | (schema.Disallow ?? JsonSchemaType.None);
|
||||
|
||||
if (schema.Pattern != null)
|
||||
{
|
||||
if (model.Patterns == null)
|
||||
model.Patterns = new List<string>();
|
||||
|
||||
model.Patterns.AddDistinct(schema.Pattern);
|
||||
}
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaModel
|
||||
{
|
||||
public bool Required { get; set; }
|
||||
public JsonSchemaType Type { get; set; }
|
||||
public int? MinimumLength { get; set; }
|
||||
public int? MaximumLength { get; set; }
|
||||
public double? DivisibleBy { get; set; }
|
||||
public double? Minimum { get; set; }
|
||||
public double? Maximum { get; set; }
|
||||
public bool ExclusiveMinimum { get; set; }
|
||||
public bool ExclusiveMaximum { get; set; }
|
||||
public int? MinimumItems { get; set; }
|
||||
public int? MaximumItems { get; set; }
|
||||
public IList<string> Patterns { get; set; }
|
||||
public IList<JsonSchemaModel> Items { get; set; }
|
||||
public IDictionary<string, JsonSchemaModel> Properties { get; set; }
|
||||
public IDictionary<string, JsonSchemaModel> PatternProperties { get; set; }
|
||||
public JsonSchemaModel AdditionalProperties { get; set; }
|
||||
public bool AllowAdditionalProperties { get; set; }
|
||||
public IList<JToken> Enum { get; set; }
|
||||
public JsonSchemaType Disallow { get; set; }
|
||||
|
||||
public JsonSchemaModel()
|
||||
{
|
||||
Type = JsonSchemaType.Any;
|
||||
AllowAdditionalProperties = true;
|
||||
Required = false;
|
||||
}
|
||||
|
||||
public static JsonSchemaModel Create(IList<JsonSchema> schemata)
|
||||
{
|
||||
JsonSchemaModel model = new JsonSchemaModel();
|
||||
|
||||
foreach (JsonSchema schema in schemata)
|
||||
{
|
||||
Combine(model, schema);
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
private static void Combine(JsonSchemaModel model, JsonSchema schema)
|
||||
{
|
||||
// Version 3 of the Draft JSON Schema has the default value of Not Required
|
||||
model.Required = model.Required || (schema.Required ?? false);
|
||||
model.Type = model.Type & (schema.Type ?? JsonSchemaType.Any);
|
||||
|
||||
model.MinimumLength = MathUtils.Max(model.MinimumLength, schema.MinimumLength);
|
||||
model.MaximumLength = MathUtils.Min(model.MaximumLength, schema.MaximumLength);
|
||||
|
||||
// not sure what is the best way to combine divisibleBy
|
||||
model.DivisibleBy = MathUtils.Max(model.DivisibleBy, schema.DivisibleBy);
|
||||
|
||||
model.Minimum = MathUtils.Max(model.Minimum, schema.Minimum);
|
||||
model.Maximum = MathUtils.Max(model.Maximum, schema.Maximum);
|
||||
model.ExclusiveMinimum = model.ExclusiveMinimum || (schema.ExclusiveMinimum ?? false);
|
||||
model.ExclusiveMaximum = model.ExclusiveMaximum || (schema.ExclusiveMaximum ?? false);
|
||||
|
||||
model.MinimumItems = MathUtils.Max(model.MinimumItems, schema.MinimumItems);
|
||||
model.MaximumItems = MathUtils.Min(model.MaximumItems, schema.MaximumItems);
|
||||
model.AllowAdditionalProperties = model.AllowAdditionalProperties && schema.AllowAdditionalProperties;
|
||||
if (schema.Enum != null)
|
||||
{
|
||||
if (model.Enum == null)
|
||||
model.Enum = new List<JToken>();
|
||||
|
||||
model.Enum.AddRangeDistinct(schema.Enum, new JTokenEqualityComparer());
|
||||
}
|
||||
model.Disallow = model.Disallow | (schema.Disallow ?? JsonSchemaType.None);
|
||||
|
||||
if (schema.Pattern != null)
|
||||
{
|
||||
if (model.Patterns == null)
|
||||
model.Patterns = new List<string>();
|
||||
|
||||
model.Patterns.AddDistinct(schema.Pattern);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,175 +1,175 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaModelBuilder
|
||||
{
|
||||
private JsonSchemaNodeCollection _nodes = new JsonSchemaNodeCollection();
|
||||
private Dictionary<JsonSchemaNode, JsonSchemaModel> _nodeModels = new Dictionary<JsonSchemaNode, JsonSchemaModel>();
|
||||
private JsonSchemaNode _node ;
|
||||
|
||||
public JsonSchemaModel Build(JsonSchema schema)
|
||||
{
|
||||
_nodes = new JsonSchemaNodeCollection();
|
||||
_node = AddSchema(null, schema);
|
||||
|
||||
_nodeModels = new Dictionary<JsonSchemaNode, JsonSchemaModel>();
|
||||
JsonSchemaModel model = BuildNodeModel(_node);
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
public JsonSchemaNode AddSchema(JsonSchemaNode existingNode, JsonSchema schema)
|
||||
{
|
||||
string newId;
|
||||
if (existingNode != null)
|
||||
{
|
||||
if (existingNode.Schemas.Contains(schema))
|
||||
return existingNode;
|
||||
|
||||
newId = JsonSchemaNode.GetId(existingNode.Schemas.Union(new[] { schema }));
|
||||
}
|
||||
else
|
||||
{
|
||||
newId = JsonSchemaNode.GetId(new[] { schema });
|
||||
}
|
||||
|
||||
if (_nodes.Contains(newId))
|
||||
return _nodes[newId];
|
||||
|
||||
JsonSchemaNode currentNode = (existingNode != null)
|
||||
? existingNode.Combine(schema)
|
||||
: new JsonSchemaNode(schema);
|
||||
|
||||
_nodes.Add(currentNode);
|
||||
|
||||
AddProperties(schema.Properties, currentNode.Properties);
|
||||
|
||||
AddProperties(schema.PatternProperties, currentNode.PatternProperties);
|
||||
|
||||
if (schema.Items != null)
|
||||
{
|
||||
for (int i = 0; i < schema.Items.Count; i++)
|
||||
{
|
||||
AddItem(currentNode, i, schema.Items[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (schema.AdditionalProperties != null)
|
||||
AddAdditionalProperties(currentNode, schema.AdditionalProperties);
|
||||
|
||||
if (schema.Extends != null)
|
||||
currentNode = AddSchema(currentNode, schema.Extends);
|
||||
|
||||
return currentNode;
|
||||
}
|
||||
|
||||
public void AddProperties(IDictionary<string, JsonSchema> source, IDictionary<string, JsonSchemaNode> target)
|
||||
{
|
||||
if (source != null)
|
||||
{
|
||||
foreach (KeyValuePair<string, JsonSchema> property in source)
|
||||
{
|
||||
AddProperty(target, property.Key, property.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AddProperty(IDictionary<string, JsonSchemaNode> target, string propertyName, JsonSchema schema)
|
||||
{
|
||||
JsonSchemaNode propertyNode;
|
||||
target.TryGetValue(propertyName, out propertyNode);
|
||||
|
||||
target[propertyName] = AddSchema(propertyNode, schema);
|
||||
}
|
||||
|
||||
public void AddItem(JsonSchemaNode parentNode, int index, JsonSchema schema)
|
||||
{
|
||||
JsonSchemaNode existingItemNode = (parentNode.Items.Count > index)
|
||||
? parentNode.Items[index]
|
||||
: null;
|
||||
|
||||
JsonSchemaNode newItemNode = AddSchema(existingItemNode, schema);
|
||||
|
||||
if (!(parentNode.Items.Count > index))
|
||||
{
|
||||
parentNode.Items.Add(newItemNode);
|
||||
}
|
||||
else
|
||||
{
|
||||
parentNode.Items[index] = newItemNode;
|
||||
}
|
||||
}
|
||||
|
||||
public void AddAdditionalProperties(JsonSchemaNode parentNode, JsonSchema schema)
|
||||
{
|
||||
parentNode.AdditionalProperties = AddSchema(parentNode.AdditionalProperties, schema);
|
||||
}
|
||||
|
||||
private JsonSchemaModel BuildNodeModel(JsonSchemaNode node)
|
||||
{
|
||||
JsonSchemaModel model;
|
||||
if (_nodeModels.TryGetValue(node, out model))
|
||||
return model;
|
||||
|
||||
model = JsonSchemaModel.Create(node.Schemas);
|
||||
_nodeModels[node] = model;
|
||||
|
||||
foreach (KeyValuePair<string, JsonSchemaNode> property in node.Properties)
|
||||
{
|
||||
if (model.Properties == null)
|
||||
model.Properties = new Dictionary<string, JsonSchemaModel>();
|
||||
|
||||
model.Properties[property.Key] = BuildNodeModel(property.Value);
|
||||
}
|
||||
foreach (KeyValuePair<string, JsonSchemaNode> property in node.PatternProperties)
|
||||
{
|
||||
if (model.PatternProperties == null)
|
||||
model.PatternProperties = new Dictionary<string, JsonSchemaModel>();
|
||||
|
||||
model.PatternProperties[property.Key] = BuildNodeModel(property.Value);
|
||||
}
|
||||
foreach (JsonSchemaNode t in node.Items)
|
||||
{
|
||||
if (model.Items == null)
|
||||
model.Items = new List<JsonSchemaModel>();
|
||||
|
||||
model.Items.Add(BuildNodeModel(t));
|
||||
}
|
||||
if (node.AdditionalProperties != null)
|
||||
model.AdditionalProperties = BuildNodeModel(node.AdditionalProperties);
|
||||
|
||||
return model;
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaModelBuilder
|
||||
{
|
||||
private JsonSchemaNodeCollection _nodes = new JsonSchemaNodeCollection();
|
||||
private Dictionary<JsonSchemaNode, JsonSchemaModel> _nodeModels = new Dictionary<JsonSchemaNode, JsonSchemaModel>();
|
||||
private JsonSchemaNode _node ;
|
||||
|
||||
public JsonSchemaModel Build(JsonSchema schema)
|
||||
{
|
||||
_nodes = new JsonSchemaNodeCollection();
|
||||
_node = AddSchema(null, schema);
|
||||
|
||||
_nodeModels = new Dictionary<JsonSchemaNode, JsonSchemaModel>();
|
||||
JsonSchemaModel model = BuildNodeModel(_node);
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
public JsonSchemaNode AddSchema(JsonSchemaNode existingNode, JsonSchema schema)
|
||||
{
|
||||
string newId;
|
||||
if (existingNode != null)
|
||||
{
|
||||
if (existingNode.Schemas.Contains(schema))
|
||||
return existingNode;
|
||||
|
||||
newId = JsonSchemaNode.GetId(existingNode.Schemas.Union(new[] { schema }));
|
||||
}
|
||||
else
|
||||
{
|
||||
newId = JsonSchemaNode.GetId(new[] { schema });
|
||||
}
|
||||
|
||||
if (_nodes.Contains(newId))
|
||||
return _nodes[newId];
|
||||
|
||||
JsonSchemaNode currentNode = (existingNode != null)
|
||||
? existingNode.Combine(schema)
|
||||
: new JsonSchemaNode(schema);
|
||||
|
||||
_nodes.Add(currentNode);
|
||||
|
||||
AddProperties(schema.Properties, currentNode.Properties);
|
||||
|
||||
AddProperties(schema.PatternProperties, currentNode.PatternProperties);
|
||||
|
||||
if (schema.Items != null)
|
||||
{
|
||||
for (int i = 0; i < schema.Items.Count; i++)
|
||||
{
|
||||
AddItem(currentNode, i, schema.Items[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (schema.AdditionalProperties != null)
|
||||
AddAdditionalProperties(currentNode, schema.AdditionalProperties);
|
||||
|
||||
if (schema.Extends != null)
|
||||
currentNode = AddSchema(currentNode, schema.Extends);
|
||||
|
||||
return currentNode;
|
||||
}
|
||||
|
||||
public void AddProperties(IDictionary<string, JsonSchema> source, IDictionary<string, JsonSchemaNode> target)
|
||||
{
|
||||
if (source != null)
|
||||
{
|
||||
foreach (KeyValuePair<string, JsonSchema> property in source)
|
||||
{
|
||||
AddProperty(target, property.Key, property.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AddProperty(IDictionary<string, JsonSchemaNode> target, string propertyName, JsonSchema schema)
|
||||
{
|
||||
JsonSchemaNode propertyNode;
|
||||
target.TryGetValue(propertyName, out propertyNode);
|
||||
|
||||
target[propertyName] = AddSchema(propertyNode, schema);
|
||||
}
|
||||
|
||||
public void AddItem(JsonSchemaNode parentNode, int index, JsonSchema schema)
|
||||
{
|
||||
JsonSchemaNode existingItemNode = (parentNode.Items.Count > index)
|
||||
? parentNode.Items[index]
|
||||
: null;
|
||||
|
||||
JsonSchemaNode newItemNode = AddSchema(existingItemNode, schema);
|
||||
|
||||
if (!(parentNode.Items.Count > index))
|
||||
{
|
||||
parentNode.Items.Add(newItemNode);
|
||||
}
|
||||
else
|
||||
{
|
||||
parentNode.Items[index] = newItemNode;
|
||||
}
|
||||
}
|
||||
|
||||
public void AddAdditionalProperties(JsonSchemaNode parentNode, JsonSchema schema)
|
||||
{
|
||||
parentNode.AdditionalProperties = AddSchema(parentNode.AdditionalProperties, schema);
|
||||
}
|
||||
|
||||
private JsonSchemaModel BuildNodeModel(JsonSchemaNode node)
|
||||
{
|
||||
JsonSchemaModel model;
|
||||
if (_nodeModels.TryGetValue(node, out model))
|
||||
return model;
|
||||
|
||||
model = JsonSchemaModel.Create(node.Schemas);
|
||||
_nodeModels[node] = model;
|
||||
|
||||
foreach (KeyValuePair<string, JsonSchemaNode> property in node.Properties)
|
||||
{
|
||||
if (model.Properties == null)
|
||||
model.Properties = new Dictionary<string, JsonSchemaModel>();
|
||||
|
||||
model.Properties[property.Key] = BuildNodeModel(property.Value);
|
||||
}
|
||||
foreach (KeyValuePair<string, JsonSchemaNode> property in node.PatternProperties)
|
||||
{
|
||||
if (model.PatternProperties == null)
|
||||
model.PatternProperties = new Dictionary<string, JsonSchemaModel>();
|
||||
|
||||
model.PatternProperties[property.Key] = BuildNodeModel(property.Value);
|
||||
}
|
||||
foreach (JsonSchemaNode t in node.Items)
|
||||
{
|
||||
if (model.Items == null)
|
||||
model.Items = new List<JsonSchemaModel>();
|
||||
|
||||
model.Items.Add(BuildNodeModel(t));
|
||||
}
|
||||
if (node.AdditionalProperties != null)
|
||||
model.AdditionalProperties = BuildNodeModel(node.AdditionalProperties);
|
||||
|
||||
return model;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,77 +1,77 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaNode
|
||||
{
|
||||
public string Id { get; private set; }
|
||||
public ReadOnlyCollection<JsonSchema> Schemas { get; private set; }
|
||||
public Dictionary<string, JsonSchemaNode> Properties { get; private set; }
|
||||
public Dictionary<string, JsonSchemaNode> PatternProperties { get; private set; }
|
||||
public List<JsonSchemaNode> Items { get; private set; }
|
||||
public JsonSchemaNode AdditionalProperties { get; set; }
|
||||
|
||||
public JsonSchemaNode(JsonSchema schema)
|
||||
{
|
||||
Schemas = new ReadOnlyCollection<JsonSchema>(new []{ schema });
|
||||
Properties = new Dictionary<string, JsonSchemaNode>();
|
||||
PatternProperties = new Dictionary<string, JsonSchemaNode>();
|
||||
Items = new List<JsonSchemaNode>();
|
||||
|
||||
Id = GetId(Schemas);
|
||||
}
|
||||
|
||||
private JsonSchemaNode(JsonSchemaNode source, JsonSchema schema)
|
||||
{
|
||||
Schemas = new ReadOnlyCollection<JsonSchema>(source.Schemas.Union(new[] { schema }).ToList());
|
||||
Properties = new Dictionary<string, JsonSchemaNode>(source.Properties);
|
||||
PatternProperties = new Dictionary<string, JsonSchemaNode>(source.PatternProperties);
|
||||
Items = new List<JsonSchemaNode>(source.Items);
|
||||
AdditionalProperties = source.AdditionalProperties;
|
||||
|
||||
Id = GetId(Schemas);
|
||||
}
|
||||
|
||||
public JsonSchemaNode Combine(JsonSchema schema)
|
||||
{
|
||||
return new JsonSchemaNode(this, schema);
|
||||
}
|
||||
|
||||
public static string GetId(IEnumerable<JsonSchema> schemata)
|
||||
{
|
||||
return string.Join("-", schemata.Select(s => s.InternalId).OrderBy(id => id, StringComparer.Ordinal).ToArray());
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaNode
|
||||
{
|
||||
public string Id { get; private set; }
|
||||
public ReadOnlyCollection<JsonSchema> Schemas { get; private set; }
|
||||
public Dictionary<string, JsonSchemaNode> Properties { get; private set; }
|
||||
public Dictionary<string, JsonSchemaNode> PatternProperties { get; private set; }
|
||||
public List<JsonSchemaNode> Items { get; private set; }
|
||||
public JsonSchemaNode AdditionalProperties { get; set; }
|
||||
|
||||
public JsonSchemaNode(JsonSchema schema)
|
||||
{
|
||||
Schemas = new ReadOnlyCollection<JsonSchema>(new []{ schema });
|
||||
Properties = new Dictionary<string, JsonSchemaNode>();
|
||||
PatternProperties = new Dictionary<string, JsonSchemaNode>();
|
||||
Items = new List<JsonSchemaNode>();
|
||||
|
||||
Id = GetId(Schemas);
|
||||
}
|
||||
|
||||
private JsonSchemaNode(JsonSchemaNode source, JsonSchema schema)
|
||||
{
|
||||
Schemas = new ReadOnlyCollection<JsonSchema>(source.Schemas.Union(new[] { schema }).ToList());
|
||||
Properties = new Dictionary<string, JsonSchemaNode>(source.Properties);
|
||||
PatternProperties = new Dictionary<string, JsonSchemaNode>(source.PatternProperties);
|
||||
Items = new List<JsonSchemaNode>(source.Items);
|
||||
AdditionalProperties = source.AdditionalProperties;
|
||||
|
||||
Id = GetId(Schemas);
|
||||
}
|
||||
|
||||
public JsonSchemaNode Combine(JsonSchema schema)
|
||||
{
|
||||
return new JsonSchemaNode(this, schema);
|
||||
}
|
||||
|
||||
public static string GetId(IEnumerable<JsonSchema> schemata)
|
||||
{
|
||||
return string.Join("-", schemata.Select(s => s.InternalId).OrderBy(id => id, StringComparer.Ordinal).ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +1,37 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaNodeCollection : KeyedCollection<string, JsonSchemaNode>
|
||||
{
|
||||
protected override string GetKeyForItem(JsonSchemaNode item)
|
||||
{
|
||||
return item.Id;
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaNodeCollection : KeyedCollection<string, JsonSchemaNode>
|
||||
{
|
||||
protected override string GetKeyForItem(JsonSchemaNode item)
|
||||
{
|
||||
return item.Id;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,65 +1,65 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolves <see cref="JsonSchema"/> from an id.
|
||||
/// </summary>
|
||||
public class JsonSchemaResolver
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the loaded schemas.
|
||||
/// </summary>
|
||||
/// <value>The loaded schemas.</value>
|
||||
public IList<JsonSchema> LoadedSchemas { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchemaResolver"/> class.
|
||||
/// </summary>
|
||||
public JsonSchemaResolver()
|
||||
{
|
||||
LoadedSchemas = new List<JsonSchema>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="JsonSchema"/> for the specified id.
|
||||
/// </summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> for the specified id.</returns>
|
||||
public virtual JsonSchema GetSchema(string id)
|
||||
{
|
||||
JsonSchema schema = LoadedSchemas.SingleOrDefault(s => s.Id == id);
|
||||
return schema;
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolves <see cref="JsonSchema"/> from an id.
|
||||
/// </summary>
|
||||
public class JsonSchemaResolver
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the loaded schemas.
|
||||
/// </summary>
|
||||
/// <value>The loaded schemas.</value>
|
||||
public IList<JsonSchema> LoadedSchemas { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonSchemaResolver"/> class.
|
||||
/// </summary>
|
||||
public JsonSchemaResolver()
|
||||
{
|
||||
LoadedSchemas = new List<JsonSchema>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="JsonSchema"/> for the specified id.
|
||||
/// </summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>A <see cref="JsonSchema"/> for the specified id.</returns>
|
||||
public virtual JsonSchema GetSchema(string id)
|
||||
{
|
||||
JsonSchema schema = LoadedSchemas.SingleOrDefault(s => s.Id == id);
|
||||
return schema;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,73 +1,73 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// The value types allowed by the <see cref="JsonSchema"/>.
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum JsonSchemaType
|
||||
{
|
||||
/// <summary>
|
||||
/// No type specified.
|
||||
/// </summary>
|
||||
None = 0,
|
||||
/// <summary>
|
||||
/// String type.
|
||||
/// </summary>
|
||||
String = 1,
|
||||
/// <summary>
|
||||
/// Float type.
|
||||
/// </summary>
|
||||
Float = 2,
|
||||
/// <summary>
|
||||
/// Integer type.
|
||||
/// </summary>
|
||||
Integer = 4,
|
||||
/// <summary>
|
||||
/// Boolean type.
|
||||
/// </summary>
|
||||
Boolean = 8,
|
||||
/// <summary>
|
||||
/// Object type.
|
||||
/// </summary>
|
||||
Object = 16,
|
||||
/// <summary>
|
||||
/// Array type.
|
||||
/// </summary>
|
||||
Array = 32,
|
||||
/// <summary>
|
||||
/// Null type.
|
||||
/// </summary>
|
||||
Null = 64,
|
||||
/// <summary>
|
||||
/// Any type.
|
||||
/// </summary>
|
||||
Any = String | Float | Integer | Boolean | Object | Array | Null
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// The value types allowed by the <see cref="JsonSchema"/>.
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum JsonSchemaType
|
||||
{
|
||||
/// <summary>
|
||||
/// No type specified.
|
||||
/// </summary>
|
||||
None = 0,
|
||||
/// <summary>
|
||||
/// String type.
|
||||
/// </summary>
|
||||
String = 1,
|
||||
/// <summary>
|
||||
/// Float type.
|
||||
/// </summary>
|
||||
Float = 2,
|
||||
/// <summary>
|
||||
/// Integer type.
|
||||
/// </summary>
|
||||
Integer = 4,
|
||||
/// <summary>
|
||||
/// Boolean type.
|
||||
/// </summary>
|
||||
Boolean = 8,
|
||||
/// <summary>
|
||||
/// Object type.
|
||||
/// </summary>
|
||||
Object = 16,
|
||||
/// <summary>
|
||||
/// Array type.
|
||||
/// </summary>
|
||||
Array = 32,
|
||||
/// <summary>
|
||||
/// Null type.
|
||||
/// </summary>
|
||||
Null = 64,
|
||||
/// <summary>
|
||||
/// Any type.
|
||||
/// </summary>
|
||||
Any = String | Float | Integer | Boolean | Object | Array | Null
|
||||
}
|
||||
}
|
||||
@@ -1,223 +1,223 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaWriter
|
||||
{
|
||||
private readonly JsonWriter _writer;
|
||||
private readonly JsonSchemaResolver _resolver;
|
||||
|
||||
public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(writer, "writer");
|
||||
_writer = writer;
|
||||
_resolver = resolver;
|
||||
}
|
||||
|
||||
private void ReferenceOrWriteSchema(JsonSchema schema)
|
||||
{
|
||||
if (schema.Id != null && _resolver.GetSchema(schema.Id) != null)
|
||||
{
|
||||
_writer.WriteStartObject();
|
||||
_writer.WritePropertyName(JsonSchemaConstants.ReferencePropertyName);
|
||||
_writer.WriteValue(schema.Id);
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
else
|
||||
{
|
||||
WriteSchema(schema);
|
||||
}
|
||||
}
|
||||
|
||||
public void WriteSchema(JsonSchema schema)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(schema, "schema");
|
||||
|
||||
if (!_resolver.LoadedSchemas.Contains(schema))
|
||||
_resolver.LoadedSchemas.Add(schema);
|
||||
|
||||
_writer.WriteStartObject();
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.RequiredPropertyName, schema.Required);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient);
|
||||
if (schema.Type != null)
|
||||
WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value);
|
||||
if (!schema.AllowAdditionalProperties)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
|
||||
_writer.WriteValue(schema.AllowAdditionalProperties);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (schema.AdditionalProperties != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
|
||||
ReferenceOrWriteSchema(schema.AdditionalProperties);
|
||||
}
|
||||
}
|
||||
WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PropertiesPropertyName, schema.Properties);
|
||||
WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PatternPropertiesPropertyName, schema.PatternProperties);
|
||||
WriteItems(schema);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMinimumPropertyName, schema.ExclusiveMinimum);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMaximumPropertyName, schema.ExclusiveMaximum);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumLengthPropertyName, schema.MinimumLength);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumLengthPropertyName, schema.MaximumLength);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumItemsPropertyName, schema.MinimumItems);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumItemsPropertyName, schema.MaximumItems);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DivisibleByPropertyName, schema.DivisibleBy);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern);
|
||||
if (schema.Enum != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName);
|
||||
_writer.WriteStartArray();
|
||||
foreach (JToken token in schema.Enum)
|
||||
{
|
||||
token.WriteTo(_writer);
|
||||
}
|
||||
_writer.WriteEndArray();
|
||||
}
|
||||
if (schema.Default != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName);
|
||||
schema.Default.WriteTo(_writer);
|
||||
}
|
||||
if (schema.Options != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.OptionsPropertyName);
|
||||
_writer.WriteStartArray();
|
||||
foreach (KeyValuePair<JToken, string> option in schema.Options)
|
||||
{
|
||||
_writer.WriteStartObject();
|
||||
_writer.WritePropertyName(JsonSchemaConstants.OptionValuePropertyName);
|
||||
option.Key.WriteTo(_writer);
|
||||
if (option.Value != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.OptionLabelPropertyName);
|
||||
_writer.WriteValue(option.Value);
|
||||
}
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
_writer.WriteEndArray();
|
||||
}
|
||||
if (schema.Disallow != null)
|
||||
WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.Value);
|
||||
if (schema.Extends != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName);
|
||||
ReferenceOrWriteSchema(schema.Extends);
|
||||
}
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
|
||||
private void WriteSchemaDictionaryIfNotNull(JsonWriter writer, string propertyName, IDictionary<string, JsonSchema> properties)
|
||||
{
|
||||
if (properties != null)
|
||||
{
|
||||
writer.WritePropertyName(propertyName);
|
||||
writer.WriteStartObject();
|
||||
foreach (KeyValuePair<string, JsonSchema> property in properties)
|
||||
{
|
||||
writer.WritePropertyName(property.Key);
|
||||
ReferenceOrWriteSchema(property.Value);
|
||||
}
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteItems(JsonSchema schema)
|
||||
{
|
||||
if (CollectionUtils.IsNullOrEmpty(schema.Items))
|
||||
return;
|
||||
|
||||
_writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName);
|
||||
|
||||
if (schema.Items.Count == 1)
|
||||
{
|
||||
ReferenceOrWriteSchema(schema.Items[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
_writer.WriteStartArray();
|
||||
foreach (JsonSchema itemSchema in schema.Items)
|
||||
{
|
||||
ReferenceOrWriteSchema(itemSchema);
|
||||
}
|
||||
_writer.WriteEndArray();
|
||||
}
|
||||
|
||||
private void WriteType(string propertyName, JsonWriter writer, JsonSchemaType type)
|
||||
{
|
||||
IList<JsonSchemaType> types;
|
||||
if (System.Enum.IsDefined(typeof(JsonSchemaType), type))
|
||||
types = new List<JsonSchemaType> { type };
|
||||
else
|
||||
types = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).ToList();
|
||||
|
||||
if (types.Count == 0)
|
||||
return;
|
||||
|
||||
writer.WritePropertyName(propertyName);
|
||||
|
||||
if (types.Count == 1)
|
||||
{
|
||||
writer.WriteValue(JsonSchemaBuilder.MapType(types[0]));
|
||||
return;
|
||||
}
|
||||
|
||||
writer.WriteStartArray();
|
||||
foreach (JsonSchemaType jsonSchemaType in types)
|
||||
{
|
||||
writer.WriteValue(JsonSchemaBuilder.MapType(jsonSchemaType));
|
||||
}
|
||||
writer.WriteEndArray();
|
||||
}
|
||||
|
||||
private void WritePropertyIfNotNull(JsonWriter writer, string propertyName, object value)
|
||||
{
|
||||
if (value != null)
|
||||
{
|
||||
writer.WritePropertyName(propertyName);
|
||||
writer.WriteValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
#if NET20
|
||||
using Newtonsoft.Json.Utilities.LinqBridge;
|
||||
#else
|
||||
using System.Linq;
|
||||
#endif
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
internal class JsonSchemaWriter
|
||||
{
|
||||
private readonly JsonWriter _writer;
|
||||
private readonly JsonSchemaResolver _resolver;
|
||||
|
||||
public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(writer, "writer");
|
||||
_writer = writer;
|
||||
_resolver = resolver;
|
||||
}
|
||||
|
||||
private void ReferenceOrWriteSchema(JsonSchema schema)
|
||||
{
|
||||
if (schema.Id != null && _resolver.GetSchema(schema.Id) != null)
|
||||
{
|
||||
_writer.WriteStartObject();
|
||||
_writer.WritePropertyName(JsonSchemaConstants.ReferencePropertyName);
|
||||
_writer.WriteValue(schema.Id);
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
else
|
||||
{
|
||||
WriteSchema(schema);
|
||||
}
|
||||
}
|
||||
|
||||
public void WriteSchema(JsonSchema schema)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(schema, "schema");
|
||||
|
||||
if (!_resolver.LoadedSchemas.Contains(schema))
|
||||
_resolver.LoadedSchemas.Add(schema);
|
||||
|
||||
_writer.WriteStartObject();
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.RequiredPropertyName, schema.Required);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient);
|
||||
if (schema.Type != null)
|
||||
WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value);
|
||||
if (!schema.AllowAdditionalProperties)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
|
||||
_writer.WriteValue(schema.AllowAdditionalProperties);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (schema.AdditionalProperties != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
|
||||
ReferenceOrWriteSchema(schema.AdditionalProperties);
|
||||
}
|
||||
}
|
||||
WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PropertiesPropertyName, schema.Properties);
|
||||
WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PatternPropertiesPropertyName, schema.PatternProperties);
|
||||
WriteItems(schema);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMinimumPropertyName, schema.ExclusiveMinimum);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMaximumPropertyName, schema.ExclusiveMaximum);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumLengthPropertyName, schema.MinimumLength);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumLengthPropertyName, schema.MaximumLength);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumItemsPropertyName, schema.MinimumItems);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumItemsPropertyName, schema.MaximumItems);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DivisibleByPropertyName, schema.DivisibleBy);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format);
|
||||
WritePropertyIfNotNull(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern);
|
||||
if (schema.Enum != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName);
|
||||
_writer.WriteStartArray();
|
||||
foreach (JToken token in schema.Enum)
|
||||
{
|
||||
token.WriteTo(_writer);
|
||||
}
|
||||
_writer.WriteEndArray();
|
||||
}
|
||||
if (schema.Default != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName);
|
||||
schema.Default.WriteTo(_writer);
|
||||
}
|
||||
if (schema.Options != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.OptionsPropertyName);
|
||||
_writer.WriteStartArray();
|
||||
foreach (KeyValuePair<JToken, string> option in schema.Options)
|
||||
{
|
||||
_writer.WriteStartObject();
|
||||
_writer.WritePropertyName(JsonSchemaConstants.OptionValuePropertyName);
|
||||
option.Key.WriteTo(_writer);
|
||||
if (option.Value != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.OptionLabelPropertyName);
|
||||
_writer.WriteValue(option.Value);
|
||||
}
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
_writer.WriteEndArray();
|
||||
}
|
||||
if (schema.Disallow != null)
|
||||
WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.Value);
|
||||
if (schema.Extends != null)
|
||||
{
|
||||
_writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName);
|
||||
ReferenceOrWriteSchema(schema.Extends);
|
||||
}
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
|
||||
private void WriteSchemaDictionaryIfNotNull(JsonWriter writer, string propertyName, IDictionary<string, JsonSchema> properties)
|
||||
{
|
||||
if (properties != null)
|
||||
{
|
||||
writer.WritePropertyName(propertyName);
|
||||
writer.WriteStartObject();
|
||||
foreach (KeyValuePair<string, JsonSchema> property in properties)
|
||||
{
|
||||
writer.WritePropertyName(property.Key);
|
||||
ReferenceOrWriteSchema(property.Value);
|
||||
}
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteItems(JsonSchema schema)
|
||||
{
|
||||
if (CollectionUtils.IsNullOrEmpty(schema.Items))
|
||||
return;
|
||||
|
||||
_writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName);
|
||||
|
||||
if (schema.Items.Count == 1)
|
||||
{
|
||||
ReferenceOrWriteSchema(schema.Items[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
_writer.WriteStartArray();
|
||||
foreach (JsonSchema itemSchema in schema.Items)
|
||||
{
|
||||
ReferenceOrWriteSchema(itemSchema);
|
||||
}
|
||||
_writer.WriteEndArray();
|
||||
}
|
||||
|
||||
private void WriteType(string propertyName, JsonWriter writer, JsonSchemaType type)
|
||||
{
|
||||
IList<JsonSchemaType> types;
|
||||
if (System.Enum.IsDefined(typeof(JsonSchemaType), type))
|
||||
types = new List<JsonSchemaType> { type };
|
||||
else
|
||||
types = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).ToList();
|
||||
|
||||
if (types.Count == 0)
|
||||
return;
|
||||
|
||||
writer.WritePropertyName(propertyName);
|
||||
|
||||
if (types.Count == 1)
|
||||
{
|
||||
writer.WriteValue(JsonSchemaBuilder.MapType(types[0]));
|
||||
return;
|
||||
}
|
||||
|
||||
writer.WriteStartArray();
|
||||
foreach (JsonSchemaType jsonSchemaType in types)
|
||||
{
|
||||
writer.WriteValue(JsonSchemaBuilder.MapType(jsonSchemaType));
|
||||
}
|
||||
writer.WriteEndArray();
|
||||
}
|
||||
|
||||
private void WritePropertyIfNotNull(JsonWriter writer, string propertyName, object value)
|
||||
{
|
||||
if (value != null)
|
||||
{
|
||||
writer.WritePropertyName(propertyName);
|
||||
writer.WriteValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +1,46 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Specifies undefined schema Id handling options for the <see cref="JsonSchemaGenerator"/>.
|
||||
/// </summary>
|
||||
public enum UndefinedSchemaIdHandling
|
||||
{
|
||||
/// <summary>
|
||||
/// Do not infer a schema Id.
|
||||
/// </summary>
|
||||
None = 0,
|
||||
/// <summary>
|
||||
/// Use the .NET type name as the schema Id.
|
||||
/// </summary>
|
||||
UseTypeName = 1,
|
||||
/// <summary>
|
||||
/// Use the assembly qualified .NET type name as the schema Id.
|
||||
/// </summary>
|
||||
UseAssemblyQualifiedName = 2,
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Specifies undefined schema Id handling options for the <see cref="JsonSchemaGenerator"/>.
|
||||
/// </summary>
|
||||
public enum UndefinedSchemaIdHandling
|
||||
{
|
||||
/// <summary>
|
||||
/// Do not infer a schema Id.
|
||||
/// </summary>
|
||||
None = 0,
|
||||
/// <summary>
|
||||
/// Use the .NET type name as the schema Id.
|
||||
/// </summary>
|
||||
UseTypeName = 1,
|
||||
/// <summary>
|
||||
/// Use the assembly qualified .NET type name as the schema Id.
|
||||
/// </summary>
|
||||
UseAssemblyQualifiedName = 2,
|
||||
}
|
||||
}
|
||||
@@ -1,71 +1,71 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns detailed information related to the <see cref="ValidationEventHandler"/>.
|
||||
/// </summary>
|
||||
public class ValidationEventArgs : EventArgs
|
||||
{
|
||||
private readonly JsonSchemaException _ex;
|
||||
|
||||
internal ValidationEventArgs(JsonSchemaException ex)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(ex, "ex");
|
||||
_ex = ex;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="JsonSchemaException"/> associated with the validation error.
|
||||
/// </summary>
|
||||
/// <value>The JsonSchemaException associated with the validation error.</value>
|
||||
public JsonSchemaException Exception
|
||||
{
|
||||
get { return _ex; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the JSON location where the validation error occurred.
|
||||
/// </summary>
|
||||
/// <value>The path of the JSON location where the validation error occurred.</value>
|
||||
public string Path
|
||||
{
|
||||
get { return _ex.Path; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the text description corresponding to the validation error.
|
||||
/// </summary>
|
||||
/// <value>The text description.</value>
|
||||
public string Message
|
||||
{
|
||||
get { return _ex.Message; }
|
||||
}
|
||||
}
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using Newtonsoft.Json.Utilities;
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns detailed information related to the <see cref="ValidationEventHandler"/>.
|
||||
/// </summary>
|
||||
public class ValidationEventArgs : EventArgs
|
||||
{
|
||||
private readonly JsonSchemaException _ex;
|
||||
|
||||
internal ValidationEventArgs(JsonSchemaException ex)
|
||||
{
|
||||
ValidationUtils.ArgumentNotNull(ex, "ex");
|
||||
_ex = ex;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="JsonSchemaException"/> associated with the validation error.
|
||||
/// </summary>
|
||||
/// <value>The JsonSchemaException associated with the validation error.</value>
|
||||
public JsonSchemaException Exception
|
||||
{
|
||||
get { return _ex; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the JSON location where the validation error occurred.
|
||||
/// </summary>
|
||||
/// <value>The path of the JSON location where the validation error occurred.</value>
|
||||
public string Path
|
||||
{
|
||||
get { return _ex.Path; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the text description corresponding to the validation error.
|
||||
/// </summary>
|
||||
/// <value>The text description.</value>
|
||||
public string Message
|
||||
{
|
||||
get { return _ex.Message; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,32 @@
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents the callback method that will handle JSON schema validation events and the <see cref="ValidationEventArgs"/>.
|
||||
/// </summary>
|
||||
public delegate void ValidationEventHandler(object sender, ValidationEventArgs e);
|
||||
#region License
|
||||
// Copyright (c) 2007 James Newton-King
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the "Software"), to deal in the Software without
|
||||
// restriction, including without limitation the rights to use,
|
||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following
|
||||
// conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
// OTHER DEALINGS IN THE SOFTWARE.
|
||||
#endregion
|
||||
|
||||
namespace Newtonsoft.Json.Schema
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents the callback method that will handle JSON schema validation events and the <see cref="ValidationEventArgs"/>.
|
||||
/// </summary>
|
||||
public delegate void ValidationEventHandler(object sender, ValidationEventArgs e);
|
||||
}
|
||||
Reference in New Issue
Block a user