-Added JSON Schema implementation

-Move test serialization objects to TestObjects namespace
-Fixed JsonConvert to always write a floating point number with a decimal place
-Changed Type values to serialize and deserialize to type name string
-Fixed JsonWriter to allow objects and arrays to be written in a constructor
-Added JsonContainerAttribute with Id, Title and Description members. JsonObject and JsonArray inherit from this attribute
-Added JsonArrayAttribute. Has flag to control whether array can contain null items.
-Added IsRequired to JsonProperty
-Replaced protected method GetSerializableMembers with GetMemberMappings on JsonSerializer
-Fixed QuoteChar not getting set when parsing property name
-Added Load(JsonReader) to JProperty, JConstructor
-Fixed error when populating JProperty with content from collection
-Added the ability for JsonTokenWriter to write individual values as well as arrays and objects
-Added CreateReader to JToken
-Added FromObject to JToken
-Added ReadFrom to JToken
This commit is contained in:
JamesNK
2009-01-02 05:29:31 +00:00
parent f95868233e
commit 0319263756
113 changed files with 8324 additions and 741 deletions
+66
View File
@@ -0,0 +1,66 @@
#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.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
public static class Extensions
{
public static bool IsValid(this JToken source, JsonSchema schema)
{
bool valid = true;
source.Validate(schema, (sender, args) => { valid = false; });
return valid;
}
public static void Validate(this JToken source, JsonSchema schema)
{
source.Validate(schema, null);
}
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())
{
}
}
}
}
}
+134
View File
@@ -0,0 +1,134 @@
#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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Schema
{
public class JsonSchema
{
public string Id { get; set; }
public string Title { get; set; }
public bool? Optional { get; set; }
public bool? ReadOnly { get; set; }
public bool? Hidden { get; set; }
public bool? Transient { get; set; }
public string Description { get; set; }
public JsonSchemaType? Type { get; set; }
public string Pattern { get; set; }
public int? MinimumLength { get; set; }
public int? MaximumLength { get; set; }
public int? MaximumDecimals { get; set; }
public double? Minimum { get; set; }
public double? Maximum { get; set; }
public int? MinimumItems { get; set; }
public int? MaximumItems { get; set; }
public IList<JsonSchema> Items { get; set; }
public IDictionary<string, JsonSchema> Properties { get; set; }
public JsonSchema AdditionalProperties { get; set; }
public bool AllowAdditionalProperties { get; set; }
public string Requires { get; set; }
public IList<string> Identity { get; set; }
public IList<JToken> Enum { get; set; }
public IDictionary<JToken, string> Options { get; set; }
public JsonSchemaType? Disallow { get; set; }
public JToken Default { get; set; }
public JsonSchema Extends { get; set; }
public string Format { get; set; }
private readonly string _internalId = Guid.NewGuid().ToString("N");
internal string InternalId
{
get { return _internalId; }
}
public JsonSchema()
{
AllowAdditionalProperties = true;
}
public static JsonSchema Read(JsonReader reader)
{
return Read(reader, new JsonSchemaResolver());
}
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);
}
public static JsonSchema Parse(string json)
{
return Parse(json, new JsonSchemaResolver());
}
public static JsonSchema Parse(string json, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(json, "json");
JsonReader reader = new JsonTextReader(new StringReader(json));
return Read(reader, resolver);
}
public void WriteTo(JsonWriter writer)
{
WriteTo(writer, new JsonSchemaResolver());
}
public void WriteTo(JsonWriter writer, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
JsonSchemaWriter schemaWriter = new JsonSchemaWriter(writer, resolver);
schemaWriter.WriteSchema(this);
}
public override string ToString()
{
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
WriteTo(jsonWriter);
return writer.ToString();
}
}
}
@@ -0,0 +1,393 @@
#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.Linq;
using System.Text;
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;
_reader.Read();
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.OptionalPropertyName:
CurrentSchema.Optional = (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.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.MaximumDecimalsPropertyName:
CurrentSchema.MaximumDecimals = Convert.ToInt32(_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 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;
}
}
}
@@ -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;
using System.Linq;
using System.Text;
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 OptionalPropertyName = "optional";
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 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 MaximumDecimalsPropertyName = "maxDecimal";
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}
};
}
}
@@ -0,0 +1,63 @@
#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>
/// Returns detailed information about the schema exception.
/// </summary>
public class JsonSchemaException : Exception
{
/// <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)
{
}
}
}
@@ -0,0 +1,334 @@
#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.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
namespace Newtonsoft.Json.Schema
{
public class JsonSchemaGenerator
{
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
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 IList<TypeSchema> _stack = new List<TypeSchema>();
private JsonSchema _currentSchema;
private Type _currentType;
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
private Type CurrentType
{
get { return _currentType; }
}
private void Push(TypeSchema typeSchema)
{
_currentType = typeSchema.Type;
_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)
{
_currentType = newValue.Type;
_currentSchema = newValue.Schema;
}
else
{
_currentType = null;
_currentSchema = null;
}
return popped;
}
public JsonSchema Generate(Type type)
{
return Generate(type, new JsonSchemaResolver(), false);
}
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{
return Generate(type, resolver, false);
}
public JsonSchema Generate(Type type, bool rootSchemaNullable)
{
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
}
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
_resolver = resolver;
return GenerateInternal(type, !rootSchemaNullable);
}
public string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
return null;
}
public string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
#if !PocketPC
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, bool valueRequired)
{
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)
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));
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
CurrentSchema.Id = explicitId;
CurrentSchema.Title = GetTitle(type);
CurrentSchema.Description = GetDescription(type);
if (CollectionUtils.IsDictionaryType(type))
{
// TODO: include null
CurrentSchema.Type = JsonSchemaType.Object;
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
// can be converted to a string
if (typeof (IConvertible).IsAssignableFrom(keyType))
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, false);
}
}
}
else if (CollectionUtils.IsCollectionType(type))
{
// TODO: include null
CurrentSchema.Type = JsonSchemaType.Array;
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
bool allowNullItem = (arrayAttribute != null) ? arrayAttribute.AllowNullItems : false;
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, !allowNullItem));
}
}
else
{
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (HasFlag(CurrentSchema.Type, JsonSchemaType.Object))
{
CurrentSchema.Id = GetTypeId(type, false);
JsonMemberMappingCollection mappings = JsonTypeReflector.GetMemberMappings(type);
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
foreach (JsonMemberMapping mapping in mappings)
{
if (!mapping.Ignored)
{
Type propertyMemberType = ReflectionUtils.GetMemberUnderlyingType(mapping.Member);
JsonSchema propertySchema = GenerateInternal(propertyMemberType, mapping.Required);
if (mapping.DefaultValue != null)
propertySchema.Default = JToken.FromObject(mapping.DefaultValue);
CurrentSchema.Properties.Add(mapping.MappingName, propertySchema);
}
}
}
else if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum)
{
CurrentSchema.Enum = new List<JToken>();
CurrentSchema.Options = new Dictionary<JToken, string>();
EnumValues<ulong> enumValues = EnumUtils.GetNamesAndValues<ulong>(type);
foreach (EnumValue<ulong> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
CurrentSchema.Options.Add(value, enumValue.Name);
}
}
}
return Pop().Schema;
}
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
{
// default value is Any
if (value == null)
return true;
return ((value & flag) == flag);
}
private JsonSchemaType GetJsonSchemaType(Type type, bool valueRequired)
{
JsonSchemaType schemaType = JsonSchemaType.None;
if (!valueRequired && ReflectionUtils.IsNullable(type))
{
schemaType = JsonSchemaType.Null;
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
}
TypeCode typeCode = Type.GetTypeCode(type);
switch (typeCode)
{
case TypeCode.Empty:
case TypeCode.Object:
if (ConvertUtils.CanConvertType(type, typeof(string), false))
return schemaType | JsonSchemaType.String;
return schemaType | JsonSchemaType.Object;
case TypeCode.DBNull:
return schemaType | JsonSchemaType.Null;
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));
}
}
}
}
@@ -0,0 +1,103 @@
#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.Linq;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaModel
{
public bool Optional { get; set; }
public JsonSchemaType Type { get; set; }
public int? MinimumLength { get; set; }
public int? MaximumLength { get; set; }
public int? MaximumDecimals { get; set; }
public double? Minimum { get; set; }
public double? Maximum { 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 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;
Optional = true;
}
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)
{
model.Optional = model.Optional && (schema.Optional ?? 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);
model.MaximumDecimals = MathUtils.Min(model.MaximumDecimals, schema.MaximumDecimals);
model.Minimum = MathUtils.Max(model.Minimum, schema.Minimum);
model.Maximum = MathUtils.Max(model.Maximum, schema.Maximum);
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);
}
}
}
}
@@ -0,0 +1,159 @@
#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.Linq;
using System.Text;
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);
if (schema.Properties != null)
{
foreach (KeyValuePair<string, JsonSchema> property in schema.Properties)
{
AddProperty(currentNode, property.Key, property.Value);
}
}
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 AddProperty(JsonSchemaNode parentNode, string propertyName, JsonSchema schema)
{
JsonSchemaNode propertyNode;
parentNode.Properties.TryGetValue(propertyName, out propertyNode);
parentNode.Properties[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);
}
for (int i = 0; i < node.Items.Count; i++)
{
if (model.Items == null)
model.Items = new List<JsonSchemaModel>();
model.Items.Add(BuildNodeModel(node.Items[i]));
}
if (node.AdditionalProperties != null)
model.AdditionalProperties = BuildNodeModel(node.AdditionalProperties);
return model;
}
}
}
@@ -0,0 +1,70 @@
#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;
using System.Linq;
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 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>();
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);
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());
}
}
}
@@ -0,0 +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;
}
}
}
@@ -0,0 +1,51 @@
#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.Linq;
using System.Net;
using System.Text;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
public class JsonSchemaResolver
{
public IList<JsonSchema> LoadedSchemas { get; protected set; }
public JsonSchemaResolver()
{
LoadedSchemas = new List<JsonSchema>();
}
public virtual JsonSchema GetSchema(string id)
{
JsonSchema schema = LoadedSchemas.SingleOrDefault(s => s.Id == id);
return schema;
}
}
}
@@ -0,0 +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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Schema
{
[Flags]
public enum JsonSchemaType
{
None = 0,
String = 1,
Float = 2,
Integer = 4,
Boolean = 8,
Object = 16,
Array = 32,
Null = 64,
Any = String | Float | Integer | Boolean | Object | Array | Null
}
}
@@ -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;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
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.OptionalPropertyName, schema.Optional);
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);
}
}
if (schema.Properties != null)
{
_writer.WritePropertyName(JsonSchemaConstants.PropertiesPropertyName);
_writer.WriteStartObject();
foreach (KeyValuePair<string, JsonSchema> property in schema.Properties)
{
_writer.WritePropertyName(property.Key);
ReferenceOrWriteSchema(property.Value);
}
_writer.WriteEndObject();
}
WriteItems(schema);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum);
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.MaximumDecimalsPropertyName, schema.MaximumDecimals);
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.OptionValuePropertyName);
_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 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);
}
}
}
}
@@ -0,0 +1,34 @@
#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
{
public enum UndefinedSchemaIdHandling
{
None = 0,
UseTypeName = 1,
UseAssemblyQualifiedName = 2,
}
}
@@ -0,0 +1,51 @@
#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
{
public class ValidationEventArgs : EventArgs
{
private readonly JsonSchemaException _ex;
internal ValidationEventArgs(JsonSchemaException ex)
{
ValidationUtils.ArgumentNotNull(ex, "ex");
_ex = ex;
}
public JsonSchemaException Exception
{
get { return _ex; }
}
public string Message
{
get { return _ex.Message; }
}
}
}
@@ -0,0 +1,29 @@
#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
{
public delegate void ValidationEventHandler(object sender, ValidationEventArgs e);
}