chore: 初始化北汽福田MES采集程序

This commit is contained in:
yexingqiang
2026-05-29 13:44:10 +08:00
commit c5e248e993
1399 changed files with 187196 additions and 0 deletions

View File

@@ -0,0 +1,137 @@
#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 Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// <para>
/// Contains the JSON schema extension methods.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
public static class Extensions
{
/// <summary>
/// <para>
/// Determines whether the <see cref="JToken"/> is valid.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </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>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
public static bool IsValid(this JToken source, JsonSchema schema)
{
bool valid = true;
source.Validate(schema, (sender, args) => { valid = false; });
return valid;
}
/// <summary>
/// <para>
/// Determines whether the <see cref="JToken"/> is valid.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </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>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
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>
/// <para>
/// Validates the specified <see cref="JToken"/>.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
/// <param name="source">The source <see cref="JToken"/> to test.</param>
/// <param name="schema">The schema to test with.</param>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
public static void Validate(this JToken source, JsonSchema schema)
{
source.Validate(schema, null);
}
/// <summary>
/// <para>
/// Validates the specified <see cref="JToken"/>.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </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>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
public static void Validate(this JToken source, JsonSchema schema, ValidationEventHandler validationEventHandler)
{
ValidationUtils.ArgumentNotNull(source, nameof(source));
ValidationUtils.ArgumentNotNull(schema, nameof(schema));
using (JsonValidatingReader reader = new JsonValidatingReader(source.CreateReader()))
{
reader.Schema = schema;
if (validationEventHandler != null)
{
reader.ValidationEventHandler += validationEventHandler;
}
while (reader.Read())
{
}
}
}
}
}

View File

@@ -0,0 +1,356 @@
#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>
/// <para>
/// An in-memory representation of a JSON Schema.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
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 a value indicating whether items in an array are validated using the <see cref="JsonSchema"/> instance at their array position from <see cref="JsonSchema.Items"/>.
/// </summary>
/// <value>
/// <c>true</c> if items are validated using their array position; otherwise, <c>false</c>.
/// </value>
public bool PositionalItemsValidation { get; set; }
/// <summary>
/// Gets or sets the <see cref="JsonSchema"/> of additional items.
/// </summary>
/// <value>The <see cref="JsonSchema"/> of additional items.</value>
public JsonSchema AdditionalItems { get; set; }
/// <summary>
/// Gets or sets a value indicating whether additional items are allowed.
/// </summary>
/// <value>
/// <c>true</c> if additional items are allowed; otherwise, <c>false</c>.
/// </value>
public bool AllowAdditionalItems { get; set; }
/// <summary>
/// Gets or sets whether the array items must be unique.
/// </summary>
public bool UniqueItems { 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 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 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 collection of <see cref="JsonSchema"/> that this schema extends.
/// </summary>
/// <value>The collection of <see cref="JsonSchema"/> that this schema extends.</value>
public IList<JsonSchema> Extends { get; set; }
/// <summary>
/// Gets or sets the format.
/// </summary>
/// <value>The format.</value>
public string Format { get; set; }
internal string Location { get; set; }
private readonly string _internalId = Guid.NewGuid().ToString("N");
internal string InternalId
{
get { return _internalId; }
}
// if this is set then this schema instance is just a deferred reference
// and will be replaced when the schema reference is resolved
internal string DeferredReference { get; set; }
internal bool ReferencesResolved { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonSchema"/> class.
/// </summary>
public JsonSchema()
{
AllowAdditionalProperties = true;
AllowAdditionalItems = 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, nameof(reader));
ValidationUtils.ArgumentNotNull(resolver, nameof(resolver));
JsonSchemaBuilder builder = new JsonSchemaBuilder(resolver);
return builder.Read(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, nameof(json));
using (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, nameof(writer));
ValidationUtils.ArgumentNotNull(resolver, nameof(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();
}
}
}

View File

@@ -0,0 +1,495 @@
#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 Newtonsoft.Json.Serialization;
#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
{
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
internal class JsonSchemaBuilder
{
private readonly IList<JsonSchema> _stack;
private readonly JsonSchemaResolver _resolver;
private readonly IDictionary<string, JsonSchema> _documentSchemas;
private JsonSchema _currentSchema;
private JObject _rootSchema;
public JsonSchemaBuilder(JsonSchemaResolver resolver)
{
_stack = new List<JsonSchema>();
_documentSchemas = new Dictionary<string, JsonSchema>();
_resolver = resolver;
}
private void Push(JsonSchema value)
{
_currentSchema = value;
_stack.Add(value);
_resolver.LoadedSchemas.Add(value);
_documentSchemas.Add(value.Location, value);
}
private JsonSchema Pop()
{
JsonSchema poppedSchema = _currentSchema;
_stack.RemoveAt(_stack.Count - 1);
_currentSchema = _stack.LastOrDefault();
return poppedSchema;
}
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
internal JsonSchema Read(JsonReader reader)
{
JToken schemaToken = JToken.ReadFrom(reader);
_rootSchema = schemaToken as JObject;
JsonSchema schema = BuildSchema(schemaToken);
ResolveReferences(schema);
return schema;
}
private string UnescapeReference(string reference)
{
return Uri.UnescapeDataString(reference).Replace("~1", "/").Replace("~0", "~");
}
private JsonSchema ResolveReferences(JsonSchema schema)
{
if (schema.DeferredReference != null)
{
string reference = schema.DeferredReference;
bool locationReference = (reference.StartsWith("#", StringComparison.Ordinal));
if (locationReference)
{
reference = UnescapeReference(reference);
}
JsonSchema resolvedSchema = _resolver.GetSchema(reference);
if (resolvedSchema == null)
{
if (locationReference)
{
string[] escapedParts = schema.DeferredReference.TrimStart('#').Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
JToken currentToken = _rootSchema;
foreach (string escapedPart in escapedParts)
{
string part = UnescapeReference(escapedPart);
if (currentToken.Type == JTokenType.Object)
{
currentToken = currentToken[part];
}
else if (currentToken.Type == JTokenType.Array || currentToken.Type == JTokenType.Constructor)
{
int index;
if (int.TryParse(part, out index) && index >= 0 && index < currentToken.Count())
{
currentToken = currentToken[index];
}
else
{
currentToken = null;
}
}
if (currentToken == null)
{
break;
}
}
if (currentToken != null)
{
resolvedSchema = BuildSchema(currentToken);
}
}
if (resolvedSchema == null)
{
throw new JsonException("Could not resolve schema reference '{0}'.".FormatWith(CultureInfo.InvariantCulture, schema.DeferredReference));
}
}
schema = resolvedSchema;
}
if (schema.ReferencesResolved)
{
return schema;
}
schema.ReferencesResolved = true;
if (schema.Extends != null)
{
for (int i = 0; i < schema.Extends.Count; i++)
{
schema.Extends[i] = ResolveReferences(schema.Extends[i]);
}
}
if (schema.Items != null)
{
for (int i = 0; i < schema.Items.Count; i++)
{
schema.Items[i] = ResolveReferences(schema.Items[i]);
}
}
if (schema.AdditionalItems != null)
{
schema.AdditionalItems = ResolveReferences(schema.AdditionalItems);
}
if (schema.PatternProperties != null)
{
foreach (KeyValuePair<string, JsonSchema> patternProperty in schema.PatternProperties.ToList())
{
schema.PatternProperties[patternProperty.Key] = ResolveReferences(patternProperty.Value);
}
}
if (schema.Properties != null)
{
foreach (KeyValuePair<string, JsonSchema> property in schema.Properties.ToList())
{
schema.Properties[property.Key] = ResolveReferences(property.Value);
}
}
if (schema.AdditionalProperties != null)
{
schema.AdditionalProperties = ResolveReferences(schema.AdditionalProperties);
}
return schema;
}
private JsonSchema BuildSchema(JToken token)
{
JObject schemaObject = token as JObject;
if (schemaObject == null)
{
throw JsonException.Create(token, token.Path, "Expected object while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
JToken referenceToken;
if (schemaObject.TryGetValue(JsonTypeReflector.RefPropertyName, out referenceToken))
{
JsonSchema deferredSchema = new JsonSchema();
deferredSchema.DeferredReference = (string)referenceToken;
return deferredSchema;
}
string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty);
if (!string.IsNullOrEmpty(location))
{
location = "/" + location;
}
location = "#" + location;
JsonSchema existingSchema;
if (_documentSchemas.TryGetValue(location, out existingSchema))
{
return existingSchema;
}
Push(new JsonSchema { Location = location });
ProcessSchemaProperties(schemaObject);
return Pop();
}
private void ProcessSchemaProperties(JObject schemaObject)
{
foreach (KeyValuePair<string, JToken> property in schemaObject)
{
switch (property.Key)
{
case JsonSchemaConstants.TypePropertyName:
CurrentSchema.Type = ProcessType(property.Value);
break;
case JsonSchemaConstants.IdPropertyName:
CurrentSchema.Id = (string)property.Value;
break;
case JsonSchemaConstants.TitlePropertyName:
CurrentSchema.Title = (string)property.Value;
break;
case JsonSchemaConstants.DescriptionPropertyName:
CurrentSchema.Description = (string)property.Value;
break;
case JsonSchemaConstants.PropertiesPropertyName:
CurrentSchema.Properties = ProcessProperties(property.Value);
break;
case JsonSchemaConstants.ItemsPropertyName:
ProcessItems(property.Value);
break;
case JsonSchemaConstants.AdditionalPropertiesPropertyName:
ProcessAdditionalProperties(property.Value);
break;
case JsonSchemaConstants.AdditionalItemsPropertyName:
ProcessAdditionalItems(property.Value);
break;
case JsonSchemaConstants.PatternPropertiesPropertyName:
CurrentSchema.PatternProperties = ProcessProperties(property.Value);
break;
case JsonSchemaConstants.RequiredPropertyName:
CurrentSchema.Required = (bool)property.Value;
break;
case JsonSchemaConstants.RequiresPropertyName:
CurrentSchema.Requires = (string)property.Value;
break;
case JsonSchemaConstants.MinimumPropertyName:
CurrentSchema.Minimum = (double)property.Value;
break;
case JsonSchemaConstants.MaximumPropertyName:
CurrentSchema.Maximum = (double)property.Value;
break;
case JsonSchemaConstants.ExclusiveMinimumPropertyName:
CurrentSchema.ExclusiveMinimum = (bool)property.Value;
break;
case JsonSchemaConstants.ExclusiveMaximumPropertyName:
CurrentSchema.ExclusiveMaximum = (bool)property.Value;
break;
case JsonSchemaConstants.MaximumLengthPropertyName:
CurrentSchema.MaximumLength = (int)property.Value;
break;
case JsonSchemaConstants.MinimumLengthPropertyName:
CurrentSchema.MinimumLength = (int)property.Value;
break;
case JsonSchemaConstants.MaximumItemsPropertyName:
CurrentSchema.MaximumItems = (int)property.Value;
break;
case JsonSchemaConstants.MinimumItemsPropertyName:
CurrentSchema.MinimumItems = (int)property.Value;
break;
case JsonSchemaConstants.DivisibleByPropertyName:
CurrentSchema.DivisibleBy = (double)property.Value;
break;
case JsonSchemaConstants.DisallowPropertyName:
CurrentSchema.Disallow = ProcessType(property.Value);
break;
case JsonSchemaConstants.DefaultPropertyName:
CurrentSchema.Default = property.Value.DeepClone();
break;
case JsonSchemaConstants.HiddenPropertyName:
CurrentSchema.Hidden = (bool)property.Value;
break;
case JsonSchemaConstants.ReadOnlyPropertyName:
CurrentSchema.ReadOnly = (bool)property.Value;
break;
case JsonSchemaConstants.FormatPropertyName:
CurrentSchema.Format = (string)property.Value;
break;
case JsonSchemaConstants.PatternPropertyName:
CurrentSchema.Pattern = (string)property.Value;
break;
case JsonSchemaConstants.EnumPropertyName:
ProcessEnum(property.Value);
break;
case JsonSchemaConstants.ExtendsPropertyName:
ProcessExtends(property.Value);
break;
case JsonSchemaConstants.UniqueItemsPropertyName:
CurrentSchema.UniqueItems = (bool)property.Value;
break;
}
}
}
private void ProcessExtends(JToken token)
{
IList<JsonSchema> schemas = new List<JsonSchema>();
if (token.Type == JTokenType.Array)
{
foreach (JToken schemaObject in token)
{
schemas.Add(BuildSchema(schemaObject));
}
}
else
{
JsonSchema schema = BuildSchema(token);
if (schema != null)
{
schemas.Add(schema);
}
}
if (schemas.Count > 0)
{
CurrentSchema.Extends = schemas;
}
}
private void ProcessEnum(JToken token)
{
if (token.Type != JTokenType.Array)
{
throw JsonException.Create(token, token.Path, "Expected Array token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
CurrentSchema.Enum = new List<JToken>();
foreach (JToken enumValue in token)
{
CurrentSchema.Enum.Add(enumValue.DeepClone());
}
}
private void ProcessAdditionalProperties(JToken token)
{
if (token.Type == JTokenType.Boolean)
{
CurrentSchema.AllowAdditionalProperties = (bool)token;
}
else
{
CurrentSchema.AdditionalProperties = BuildSchema(token);
}
}
private void ProcessAdditionalItems(JToken token)
{
if (token.Type == JTokenType.Boolean)
{
CurrentSchema.AllowAdditionalItems = (bool)token;
}
else
{
CurrentSchema.AdditionalItems = BuildSchema(token);
}
}
private IDictionary<string, JsonSchema> ProcessProperties(JToken token)
{
IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();
if (token.Type != JTokenType.Object)
{
throw JsonException.Create(token, token.Path, "Expected Object token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
foreach (JProperty propertyToken in token)
{
if (properties.ContainsKey(propertyToken.Name))
{
throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyToken.Name));
}
properties.Add(propertyToken.Name, BuildSchema(propertyToken.Value));
}
return properties;
}
private void ProcessItems(JToken token)
{
CurrentSchema.Items = new List<JsonSchema>();
switch (token.Type)
{
case JTokenType.Object:
CurrentSchema.Items.Add(BuildSchema(token));
CurrentSchema.PositionalItemsValidation = false;
break;
case JTokenType.Array:
CurrentSchema.PositionalItemsValidation = true;
foreach (JToken schemaToken in token)
{
CurrentSchema.Items.Add(BuildSchema(schemaToken));
}
break;
default:
throw JsonException.Create(token, token.Path, "Expected array or JSON schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
}
private JsonSchemaType? ProcessType(JToken token)
{
switch (token.Type)
{
case JTokenType.Array:
// ensure type is in blank state before ORing values
JsonSchemaType? type = JsonSchemaType.None;
foreach (JToken typeToken in token)
{
if (typeToken.Type != JTokenType.String)
{
throw JsonException.Create(typeToken, typeToken.Path, "Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
type = type | MapType((string)typeToken);
}
return type;
case JTokenType.String:
return MapType((string)token);
default:
throw JsonException.Create(token, token.Path, "Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
}
internal static JsonSchemaType MapType(string type)
{
JsonSchemaType mappedType;
if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType))
{
throw new JsonException("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;
}
}
}

View File

@@ -0,0 +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;
using System.Collections.Generic;
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
internal static class JsonSchemaConstants
{
public const string TypePropertyName = "type";
public const string PropertiesPropertyName = "properties";
public const string ItemsPropertyName = "items";
public const string AdditionalItemsPropertyName = "additionalItems";
public const string RequiredPropertyName = "required";
public const string PatternPropertiesPropertyName = "patternProperties";
public const string AdditionalPropertiesPropertyName = "additionalProperties";
public const string RequiresPropertyName = "requires";
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 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 UniqueItemsPropertyName = "uniqueItems";
public const string OptionValuePropertyName = "value";
public const string OptionLabelPropertyName = "label";
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 }
};
}
}

View File

@@ -0,0 +1,113 @@
#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>
/// <para>
/// Returns detailed information about the schema exception.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
#if !(DOTNET || PORTABLE40 || PORTABLE)
[Serializable]
#endif
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
public class JsonSchemaException : JsonException
{
/// <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 !(DOTNET || PORTABLE40 || PORTABLE)
/// <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;
}
}
}

View File

@@ -0,0 +1,515 @@
#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 NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// <para>
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
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, nameof(type));
ValidationUtils.ArgumentNotNull(schema, nameof(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, nameof(type));
ValidationUtils.ArgumentNotNull(resolver, nameof(resolver));
_resolver = resolver;
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
}
private string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
{
return containerAttribute.Title;
}
return null;
}
private string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
{
return containerAttribute.Description;
}
#if !(DOTNET || PORTABLE40 || PORTABLE)
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.GetCachedAttribute<JsonContainerAttribute>(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, nameof(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 JsonException("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.GetCachedAttribute<JsonArrayAttribute>(type);
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>();
IList<EnumValue<long>> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
}
}
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)
{
JsonContract keyContract = ContractResolver.ResolveContract(keyType);
// can be converted to a string
if (keyContract.ContractType == JsonContractType.Primitive)
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
}
}
break;
#if !(DOTNET || PORTABLE || PORTABLE40)
case JsonContractType.Serializable:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateISerializableContract(type, (JsonISerializableContract)contract);
break;
#endif
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
#endif
case JsonContractType.Linq:
CurrentSchema.Type = JsonSchemaType.Any;
break;
default:
throw new JsonException("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 !(DOTNET || PORTABLE || PORTABLE40)
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 (flag == JsonSchemaType.Integer && (value & JsonSchemaType.Float) == JsonSchemaType.Float)
{
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);
}
}
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type);
switch (typeCode)
{
case PrimitiveTypeCode.Empty:
case PrimitiveTypeCode.Object:
return schemaType | JsonSchemaType.String;
#if !(DOTNET || PORTABLE)
case PrimitiveTypeCode.DBNull:
return schemaType | JsonSchemaType.Null;
#endif
case PrimitiveTypeCode.Boolean:
return schemaType | JsonSchemaType.Boolean;
case PrimitiveTypeCode.Char:
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.SByte:
case PrimitiveTypeCode.Byte:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.UInt32:
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
#if !(PORTABLE || NET35 || NET20)
case PrimitiveTypeCode.BigInteger:
#endif
return schemaType | JsonSchemaType.Integer;
case PrimitiveTypeCode.Single:
case PrimitiveTypeCode.Double:
case PrimitiveTypeCode.Decimal:
return schemaType | JsonSchemaType.Float;
// convert to string?
case PrimitiveTypeCode.DateTime:
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
#endif
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.String:
case PrimitiveTypeCode.Uri:
case PrimitiveTypeCode.Guid:
case PrimitiveTypeCode.TimeSpan:
case PrimitiveTypeCode.Bytes:
return schemaType | JsonSchemaType.String;
default:
throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
}
}
}
}

View File

@@ -0,0 +1,125 @@
#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 Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
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 JsonSchemaModel AdditionalItems { get; set; }
public bool PositionalItemsValidation { get; set; }
public bool AllowAdditionalProperties { get; set; }
public bool AllowAdditionalItems { get; set; }
public bool UniqueItems { get; set; }
public IList<JToken> Enum { get; set; }
public JsonSchemaType Disallow { get; set; }
public JsonSchemaModel()
{
Type = JsonSchemaType.Any;
AllowAdditionalProperties = true;
AllowAdditionalItems = 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.PositionalItemsValidation = model.PositionalItemsValidation || schema.PositionalItemsValidation;
model.AllowAdditionalProperties = model.AllowAdditionalProperties && schema.AllowAdditionalProperties;
model.AllowAdditionalItems = model.AllowAdditionalItems && schema.AllowAdditionalItems;
model.UniqueItems = model.UniqueItems || schema.UniqueItems;
if (schema.Enum != null)
{
if (model.Enum == null)
{
model.Enum = new List<JToken>();
}
model.Enum.AddRangeDistinct(schema.Enum, JToken.EqualityComparer);
}
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);
}
}
}
}

View File

@@ -0,0 +1,213 @@
#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
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
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.AdditionalItems != null)
{
AddAdditionalItems(currentNode, schema.AdditionalItems);
}
if (schema.AdditionalProperties != null)
{
AddAdditionalProperties(currentNode, schema.AdditionalProperties);
}
if (schema.Extends != null)
{
foreach (JsonSchema jsonSchema in schema.Extends)
{
currentNode = AddSchema(currentNode, jsonSchema);
}
}
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);
}
public void AddAdditionalItems(JsonSchemaNode parentNode, JsonSchema schema)
{
parentNode.AdditionalItems = AddSchema(parentNode.AdditionalItems, 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);
}
if (node.AdditionalItems != null)
{
model.AdditionalItems = BuildNodeModel(node.AdditionalItems);
}
return model;
}
}
}

View File

@@ -0,0 +1,81 @@
#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
{
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
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 AdditionalItems { 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;
AdditionalItems = source.AdditionalItems;
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());
}
}
}

View File

@@ -0,0 +1,39 @@
#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.ObjectModel;
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
internal class JsonSchemaNodeCollection : KeyedCollection<string, JsonSchemaNode>
{
protected override string GetKeyForItem(JsonSchemaNode item)
{
return item.Id;
}
}
}

View File

@@ -0,0 +1,79 @@
#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
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// <para>
/// Resolves <see cref="JsonSchema"/> from an id.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
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 reference.
/// </summary>
/// <param name="reference">The id.</param>
/// <returns>A <see cref="JsonSchema"/> for the specified reference.</returns>
public virtual JsonSchema GetSchema(string reference)
{
JsonSchema schema = LoadedSchemas.SingleOrDefault(s => string.Equals(s.Id, reference, StringComparison.Ordinal));
if (schema == null)
{
schema = LoadedSchemas.SingleOrDefault(s => string.Equals(s.Location, reference, StringComparison.Ordinal));
}
return schema;
}
}
}

View File

@@ -0,0 +1,87 @@
#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>
/// <para>
/// The value types allowed by the <see cref="JsonSchema"/>.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
[Flags]
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
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
}
}

View File

@@ -0,0 +1,259 @@
#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 Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
internal class JsonSchemaWriter
{
private readonly JsonWriter _writer;
private readonly JsonSchemaResolver _resolver;
public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(writer, nameof(writer));
_writer = writer;
_resolver = resolver;
}
private void ReferenceOrWriteSchema(JsonSchema schema)
{
if (schema.Id != null && _resolver.GetSchema(schema.Id) != null)
{
_writer.WriteStartObject();
_writer.WritePropertyName(JsonTypeReflector.RefPropertyName);
_writer.WriteValue(schema.Id);
_writer.WriteEndObject();
}
else
{
WriteSchema(schema);
}
}
public void WriteSchema(JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(schema, nameof(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.GetValueOrDefault());
}
if (!schema.AllowAdditionalProperties)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
_writer.WriteValue(schema.AllowAdditionalProperties);
}
else
{
if (schema.AdditionalProperties != null)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
ReferenceOrWriteSchema(schema.AdditionalProperties);
}
}
if (!schema.AllowAdditionalItems)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName);
_writer.WriteValue(schema.AllowAdditionalItems);
}
else
{
if (schema.AdditionalItems != null)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName);
ReferenceOrWriteSchema(schema.AdditionalItems);
}
}
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.Disallow != null)
{
WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.GetValueOrDefault());
}
if (schema.Extends != null && schema.Extends.Count > 0)
{
_writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName);
if (schema.Extends.Count == 1)
{
ReferenceOrWriteSchema(schema.Extends[0]);
}
else
{
_writer.WriteStartArray();
foreach (JsonSchema jsonSchema in schema.Extends)
{
ReferenceOrWriteSchema(jsonSchema);
}
_writer.WriteEndArray();
}
}
_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 (schema.Items == null && !schema.PositionalItemsValidation)
{
return;
}
_writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName);
if (!schema.PositionalItemsValidation)
{
if (schema.Items != null && schema.Items.Count > 0)
{
ReferenceOrWriteSchema(schema.Items[0]);
}
else
{
_writer.WriteStartObject();
_writer.WriteEndObject();
}
return;
}
_writer.WriteStartArray();
if (schema.Items != null)
{
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);
}
}
}
}

View File

@@ -0,0 +1,56 @@
#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>
/// <para>
/// Specifies undefined schema Id handling options for the <see cref="JsonSchemaGenerator"/>.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
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,
}
}

View File

@@ -0,0 +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 Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// <para>
/// Returns detailed information related to the <see cref="ValidationEventHandler"/>.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
public class ValidationEventArgs : EventArgs
{
private readonly JsonSchemaException _ex;
internal ValidationEventArgs(JsonSchemaException ex)
{
ValidationUtils.ArgumentNotNull(ex, nameof(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; }
}
}
}

View File

@@ -0,0 +1,40 @@
#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>
/// <para>
/// Represents the callback method that will handle JSON schema validation events and the <see cref="ValidationEventArgs"/>.
/// </para>
/// <note type="caution">
/// JSON Schema validation has been moved to its own package. See <see href="http://www.newtonsoft.com/jsonschema">http://www.newtonsoft.com/jsonschema</see> for more details.
/// </note>
/// </summary>
[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
public delegate void ValidationEventHandler(object sender, ValidationEventArgs e);
}