internal IList<CodeMemberProperty> GenerateAllProperties(string name, JsonSchema schema, IDictionary<JsonSchema, SchemaImplementationDetails> implDetails, INestedClassProvider internalClassProvider, params string[] usedWordsInContext) { schema.ThrowIfNull("schema"); name.ThrowIfNullOrEmpty("name"); logger.Debug("Adding properties for {0}", name); var fields = new List<CodeMemberProperty>(); if (schema.Properties.IsNullOrEmpty()) { logger.Debug("No properties found for schema " + name); return fields; } IEnumerable<string> allUsedWordsInContext = usedWordsInContext.Concat(schema.Properties.Keys); int index = 0; foreach (var propertyPair in schema.Properties) { SchemaImplementationDetails details = implDetails[propertyPair.Value]; CodeMemberProperty property = GenerateProperty( propertyPair.Key, propertyPair.Value, details, index++, internalClassProvider, allUsedWordsInContext.Except(new[] { propertyPair.Key })); fields.Add(property); } return fields; }
protected string CreateInstanceFromSchema(JsonSchema schema, int indent) { if (schema.Type == JsonSchemaType.Array) { var items = schema.Items != null ? schema.Items.Select(i => CreateInstanceFromSchema(i, indent+1)) : Enumerable.Empty<string>(); return Indent(indent) + "[\n" + string.Join(",\n", items) + Indent(indent) + "]\n"; } if (schema.Type == JsonSchemaType.Object || schema.Type == null) { var properties = schema.Properties != null ? schema.Properties.Select(i => CreateInstanceFromProperty(i, indent+1)) : Enumerable.Empty<string>(); return Indent(indent) + "{\n" + string.Join(",\n", properties) + "\n" + Indent(indent) + "}\n"; } if (schema.Type == JsonSchemaType.String) { return Indent(indent) + "\"\""; } if (schema.Type == JsonSchemaType.Integer) { return Indent(indent) + "0"; } if (schema.Type == JsonSchemaType.Boolean) { return Indent(indent) + "false"; } return ""; }
public JsonSchemaModel Build(JsonSchema schema) { this._nodes = new JsonSchemaNodeCollection(); this._node = this.AddSchema((JsonSchemaNode) null, schema); this._nodeModels = new Dictionary<JsonSchemaNode, JsonSchemaModel>(); return this.BuildNodeModel(this._node); }
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; }
internal static CodeTypeReference GetArrayTypeReference(JsonSchema propertySchema, SchemaImplementationDetails details, INestedClassProvider internalClassProvider) { propertySchema.ThrowIfNull("propertySchema"); if (propertySchema.Type != JsonSchemaType.Array) { throw new ArgumentException("Must be of JsonSchemaType.Array", "propertySchema"); } var arrayItems = propertySchema.Items; if (arrayItems != null && arrayItems.Count == 1) { CodeTypeReference itemType = arrayItems[0].Id.IsNotNullOrEmpty() ? new CodeTypeReference(arrayItems[0].Id) : GetCodeType(arrayItems[0], details, internalClassProvider); logger.Debug("type for array {0}", itemType.BaseType); return new CodeTypeReference(typeof(IList<>)) { TypeArguments = { itemType } }; } logger.Warning("Found Array of unhandled type. {0}", propertySchema); return new CodeTypeReference(typeof(System.Collections.IList)); }
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); } }
/// <summary> /// Returns a code type references for the specified json schema. /// Generates the appropriate references. /// </summary> internal static CodeTypeReference GetCodeType(JsonSchema propertySchema, SchemaImplementationDetails details, INestedClassProvider internalClassProvider) { propertySchema.ThrowIfNull("propertySchema"); internalClassProvider.ThrowIfNull("internalClassProvider"); if (propertySchema.Type.HasValue == false) { throw new NotSupportedException("propertySchema has no Type. " + propertySchema); } switch (propertySchema.Type.Value) { case JsonSchemaType.String: return new CodeTypeReference(typeof(string)); case JsonSchemaType.Integer: return new CodeTypeReference(typeof(long?)); case JsonSchemaType.Boolean: return new CodeTypeReference(typeof(bool?)); case JsonSchemaType.Float: return new CodeTypeReference(typeof(double?)); case JsonSchemaType.Array: return GetArrayTypeReference(propertySchema, details, internalClassProvider); case JsonSchemaType.Object: return GetObjectTypeReference(propertySchema, details, internalClassProvider); case JsonSchemaType.Any: return new CodeTypeReference(typeof(string)); default: logger.Warning( "Found currently unsupported type {0} as part of {1}", propertySchema.Type.Value, propertySchema); return new CodeTypeReference(typeof(object)); } }
public void AddProperty(IDictionary<string, JsonSchemaNode> target, string propertyName, JsonSchema schema) { JsonSchemaNode propertyNode; target.TryGetValue(propertyName, out propertyNode); target[propertyName] = AddSchema(propertyNode, schema); }
private JsonSchema Pop() { JsonSchema jsonSchema = this._currentSchema; this._stack.RemoveAt(this._stack.Count - 1); this._currentSchema = Enumerable.LastOrDefault<JsonSchema>((IEnumerable<JsonSchema>) this._stack); return jsonSchema; }
internal IList<CodeMemberField> GenerateAllFields(string name, JsonSchema schema, IDictionary<JsonSchema, SchemaImplementationDetails> implDetails, INestedClassProvider internalClassProvider) { schema.ThrowIfNull("schema"); name.ThrowIfNull("name"); implDetails.ThrowIfNull("details"); internalClassProvider.ThrowIfNull("internalClassProvider"); var fields = new List<CodeMemberField>(); if (schema.Properties.IsNullOrEmpty()) { logger.Debug("No Properties found for " + name); return fields; } int index = 0; foreach (var propertyPair in schema.Properties) { SchemaImplementationDetails details = implDetails[propertyPair.Value]; fields.Add( GenerateField( propertyPair.Key, propertyPair.Value, details, index, internalClassProvider, schema.Properties.Keys.Without(propertyPair.Key))); index++; } return fields; }
public void AddProperty(JsonSchemaNode parentNode, string propertyName, JsonSchema schema) { JsonSchemaNode propertyNode; parentNode.Properties.TryGetValue(propertyName, out propertyNode); parentNode.Properties[propertyName] = AddSchema(propertyNode, schema); }
private SchemaPropertyType getPropertyType(Newtonsoft.Json.Schema.JsonSchema value) { var schemaType = value.Type.Value; if (schemaType == JsonSchemaType.Boolean) { return(SchemaPropertyType.Boolean); } if (schemaType == JsonSchemaType.Integer) { return(SchemaPropertyType.Boolean); } if (schemaType == JsonSchemaType.Float) { return(SchemaPropertyType.Float); } if (schemaType == JsonSchemaType.String) { return(SchemaPropertyType.String); } return(SchemaPropertyType.Object); }
public static bool IsValid(this JToken source, JsonSchema schema, out IList<string> errorMessages) { IList<string> errors = (IList<string>) new List<string>(); Extensions.Validate(source, schema, (ValidationEventHandler) ((sender, args) => errors.Add(args.Message))); errorMessages = errors; return errorMessages.Count == 0; }
private void Push(JsonSchema value) { _currentSchema = value; _stack.Add(value); _resolver.LoadedSchemas.Add(value); _documentSchemas.Add(value.Location, value); }
public JsonSchemaNode AddSchema(JsonSchemaNode existingNode, JsonSchema schema) { string id; if (existingNode != null) { if (existingNode.Schemas.Contains(schema)) return existingNode; id = JsonSchemaNode.GetId(Enumerable.Union<JsonSchema>((IEnumerable<JsonSchema>) existingNode.Schemas, (IEnumerable<JsonSchema>) new JsonSchema[1] { schema })); } else id = JsonSchemaNode.GetId((IEnumerable<JsonSchema>) new JsonSchema[1] { schema }); if (this._nodes.Contains(id)) return this._nodes[id]; JsonSchemaNode jsonSchemaNode = existingNode != null ? existingNode.Combine(schema) : new JsonSchemaNode(schema); this._nodes.Add(jsonSchemaNode); this.AddProperties(schema.Properties, (IDictionary<string, JsonSchemaNode>) jsonSchemaNode.Properties); this.AddProperties(schema.PatternProperties, (IDictionary<string, JsonSchemaNode>) jsonSchemaNode.PatternProperties); if (schema.Items != null) { for (int index = 0; index < schema.Items.Count; ++index) this.AddItem(jsonSchemaNode, index, schema.Items[index]); } if (schema.AdditionalProperties != null) this.AddAdditionalProperties(jsonSchemaNode, schema.AdditionalProperties); if (schema.Extends != null) jsonSchemaNode = this.AddSchema(jsonSchemaNode, schema.Extends); return jsonSchemaNode; }
/// <summary> /// 转化为markdown格式。 /// </summary> /// <param name="schema"></param> /// <returns></returns> public static string AsMarkdown(JsonSchema schema) { var sb = new StringBuilder(); // 生成表格 sb.AppendLine(AsMarkdown(schema, 1).Trim()); // 生成例子 sb.AppendLine(); sb.AppendLine("例子"); sb.AppendLine(); JToken demoToken = JsonDemoGenerator.Generate(schema); string demo = JsonConvert.SerializeObject(demoToken, Formatting.Indented); // 每一行前+4个空格,以适应markdown的code格式。 var sr = new StringReader(demo); string line = sr.ReadLine(); while (!string.IsNullOrEmpty(line)) { sb.AppendLine(" " + line); line = sr.ReadLine(); } return sb.ToString(); }
private JsonSchema Pop() { JsonSchema poppedSchema = _currentSchema; _stack.RemoveAt(_stack.Count - 1); _currentSchema = _stack.LastOrDefault(); return poppedSchema; }
public JsonSchemaNode(JsonSchema schema) { Schemas = new ReadOnlyCollection<JsonSchema>(new []{ schema }); Properties = new Dictionary<string, JsonSchemaNode>(); Items = new List<JsonSchemaNode>(); Id = GetId(Schemas); }
public void DecorateInternalClass(CodeTypeDeclaration typeDeclaration, string name, JsonSchema schema, IDictionary<JsonSchema, SchemaImplementationDetails> implDetails, INestedClassProvider internalClassProvider) { ImplementAdditionalProperties(typeDeclaration, schema, implDetails, internalClassProvider); }
private JsonSchemaGenerator.TypeSchema Pop() { JsonSchemaGenerator.TypeSchema typeSchema1 = this._stack[this._stack.Count - 1]; this._stack.RemoveAt(this._stack.Count - 1); JsonSchemaGenerator.TypeSchema typeSchema2 = Enumerable.LastOrDefault<JsonSchemaGenerator.TypeSchema>((IEnumerable<JsonSchemaGenerator.TypeSchema>) this._stack); this._currentSchema = typeSchema2 == null ? (JsonSchema) null : typeSchema2.Schema; return typeSchema1; }
public void AddItem(JsonSchemaNode parentNode, int index, JsonSchema schema) { JsonSchemaNode jsonSchemaNode = this.AddSchema(parentNode.Items.Count > index ? parentNode.Items[index] : (JsonSchemaNode) null, schema); if (parentNode.Items.Count <= index) parentNode.Items.Add(jsonSchemaNode); else parentNode.Items[index] = jsonSchemaNode; }
public TypeSchema(Type type, JsonSchema schema) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(schema, "schema"); Type = type; Schema = schema; }
public TypeSchema(Type type, JsonSchema schema) { ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(schema, nameof(schema)); Type = type; Schema = schema; }
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); }
/// <summary> /// Get the array type for the given schema. /// </summary> /// <param name="schema">The schema.</param> /// <exception cref="System.NotSupportedException">Thrown when given schema is not an array type.</exception> /// <returns>The array type of the schema.</returns> public static ArrayType GetArrayType(JsonSchema schema) { if (!IsArray(schema)) { throw new NotSupportedException(); } return schema.UniqueItems ? ArrayType.HashSet : ArrayType.List; }
/// <summary> /// Determines whether the <see cref="JToken"/> is valid. /// </summary> /// <param name="source">The source <see cref="JToken"/> to test.</param> /// <param name="schema">The schema to test with.</param> /// <param name="errorMessages">When this method returns, contains any error messages generated while validating. </param> /// <returns> /// <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>. /// </returns> public static bool IsValid(this JToken source, JsonSchema schema, out IList<string> errorMessages) { IList<string> errors = new List<string>(); source.Validate(schema, (sender, args) => errors.Add(args.Message)); errorMessages = errors; return (errorMessages.Count == 0); }
public static bool IsValid(JToken source, JsonSchema schema) { bool valid = true; Extensions.Validate(source, schema, delegate(object sender, ValidationEventArgs e) { valid = false; }); return valid; }
public JsonSchemaModel Build(JsonSchema schema) { _nodes = new JsonSchemaNodeCollection(); _node = AddSchema(null, schema); _nodeModels = new Dictionary<JsonSchemaNode, JsonSchemaModel>(); JsonSchemaModel model = BuildNodeModel(_node); return model; }
public static bool IsValid(JToken source, JsonSchema schema, out IList<string> errorMessages) { IList<string> errors = new List<string>(); Extensions.Validate(source, schema, delegate(object sender, ValidationEventArgs e) { errors.Add(e.Message); }); errorMessages = errors; return errorMessages.Count == 0; }
public void ResolvePassTest() { var actual = new FutureJsonSchema("123ABC"); var sucess = new JsonSchema { Id = "123ABC", Maximum = 12.5, Minimum = 5.3 }; actual.Resolve(sucess); Assert.True(actual.Resolved); Assert.AreEqual(12.5, actual.Maximum.Value); Assert.AreEqual(5.3, actual.Minimum.Value); }
public JsonSchemaNode(JsonSchema schema) { this.Schemas = new ReadOnlyCollection<JsonSchema>((IList<JsonSchema>) new JsonSchema[1] { schema }); this.Properties = new Dictionary<string, JsonSchemaNode>(); this.PatternProperties = new Dictionary<string, JsonSchemaNode>(); this.Items = new List<JsonSchemaNode>(); this.Id = JsonSchemaNode.GetId((IEnumerable<JsonSchema>) this.Schemas); }
private ValidatedPropertyMetadata getValidatedPropertyMetadata (Newtonsoft.Json.Schema.JsonSchema value, SchemaPropertyType propertyType) { var result = new ValidatedPropertyMetadata(propertyType); if (value.ExclusiveMaximum.HasValue) { result.ExclusiveMaximum = value.ExclusiveMaximum; } if (value.ExclusiveMinimum.HasValue) { result.ExclusiveMinimum = value.ExclusiveMinimum; } if (value.Maximum.HasValue) { result.Maximum = value.Maximum; } if (value.MaximumLength.HasValue) { result.MaximumLength = value.MaximumLength; } if (value.Minimum.HasValue) { result.Minimum = value.Minimum; } if (value.MinimumLength.HasValue) { result.MinimumLength = value.MinimumLength; } if (!string.IsNullOrWhiteSpace(value.Pattern)) { result.Pattern = value.Pattern; } if (value.Required.HasValue) { result.Required = value.Required; } return(result); }
private bool isPropertyValidated(Newtonsoft.Json.Schema.JsonSchema value) { var result = false; if (value.ExclusiveMaximum.HasValue) { result = true; } if (value.ExclusiveMinimum.HasValue) { result = true; } if (value.Maximum.HasValue) { result = true; } if (value.MaximumLength.HasValue) { result = true; } if (value.Minimum.HasValue) { result = true; } if (value.MinimumLength.HasValue) { result = true; } if (!string.IsNullOrWhiteSpace(value.Pattern)) { result = true; } if (value.Required.HasValue) { result = true; } return(result); }
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 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; if (MappingResolver != null) { mappings = MappingResolver.ResolveMappings(type); } else { mappings = DefaultMappingResolver.Instance.ResolveMappings(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); } } if (type.IsSealed) { CurrentSchema.AllowAdditionalProperties = false; } } else if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof(FlagsAttribute), true)) { 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); }
/// <summary> /// Determines whether the <see cref="JToken"/> is valid. /// </summary> /// <param name="source">The source <see cref="JToken"/> to test.</param> /// <param name="schema">The schema to test with.</param> /// <returns> /// <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>. /// </returns> public static bool IsValid(this JToken source, JsonSchema schema) { bool valid = true; source.Validate(schema, (sender, args) => { valid = false; }); return valid; }
public JsonSchemaNode Combine(JsonSchema schema) { return(new JsonSchemaNode(this, schema)); }
public void WriteSchema(JsonSchema schema) { ValidationUtils.ArgumentNotNull(schema, "schema"); if (!_resolver.LoadedSchemas.Contains(schema)) { _resolver.LoadedSchemas.Add(schema); } _writer.WriteStartObject(); WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id); WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title); WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description); WritePropertyIfNotNull(_writer, JsonSchemaConstants.RequiredPropertyName, schema.Required); WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly); WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden); WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient); if (schema.Type != null) { WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value); } if (!schema.AllowAdditionalProperties) { _writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName); _writer.WriteValue(schema.AllowAdditionalProperties); } else { if (schema.AdditionalProperties != null) { _writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName); ReferenceOrWriteSchema(schema.AdditionalProperties); } } 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.Value); } 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 Push(JsonSchemaGenerator.TypeSchema typeSchema) { this._currentSchema = typeSchema.Schema; this._stack.Add(typeSchema); this._resolver.LoadedSchemas.Add(typeSchema.Schema); }
/// <summary> /// Gets a <see cref="JsonSchema"/> for the specified id. /// </summary> /// <param name="id">The id.</param> /// <returns>A <see cref="JsonSchema"/> for the specified id.</returns> public virtual JsonSchema GetSchema(string id) { JsonSchema schema = LoadedSchemas.SingleOrDefault(s => s.Id == id); return(schema); }
private static void Combine(JsonSchemaModel model, JsonSchema schema) { bool required2; if (!model.Required) { bool?required = schema.Required; required2 = (required != null && required.Value); } else { required2 = true; } model.Required = required2; JsonSchemaType type = model.Type; JsonSchemaType?type2 = schema.Type; model.Type = (type & ((type2 == null) ? JsonSchemaType.Any : type2.Value)); model.MinimumLength = MathUtils.Max(model.MinimumLength, schema.MinimumLength); model.MaximumLength = MathUtils.Min(model.MaximumLength, schema.MaximumLength); model.DivisibleBy = MathUtils.Max(model.DivisibleBy, schema.DivisibleBy); model.Minimum = MathUtils.Max(model.Minimum, schema.Minimum); model.Maximum = MathUtils.Max(model.Maximum, schema.Maximum); bool exclusiveMinimum2; if (!model.ExclusiveMinimum) { bool?exclusiveMinimum = schema.ExclusiveMinimum; exclusiveMinimum2 = (exclusiveMinimum != null && exclusiveMinimum.Value); } else { exclusiveMinimum2 = true; } model.ExclusiveMinimum = exclusiveMinimum2; bool exclusiveMaximum2; if (!model.ExclusiveMaximum) { bool?exclusiveMaximum = schema.ExclusiveMaximum; exclusiveMaximum2 = (exclusiveMaximum != null && exclusiveMaximum.Value); } else { exclusiveMaximum2 = true; } model.ExclusiveMaximum = exclusiveMaximum2; 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()); } JsonSchemaType disallow = model.Disallow; JsonSchemaType?disallow2 = schema.Disallow; model.Disallow = (disallow | ((disallow2 == null) ? JsonSchemaType.None : disallow2.Value)); if (schema.Pattern != null) { if (model.Patterns == null) { model.Patterns = new List <string>(); } model.Patterns.AddDistinct(schema.Pattern); } }
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 AddProperty(IDictionary <string, JsonSchemaNode> target, string propertyName, JsonSchema schema) { JsonSchemaNode propertyNode; target.TryGetValue(propertyName, out propertyNode); target[propertyName] = AddSchema(propertyNode, schema); }
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); }
public static void Validate(this JToken source, JsonSchema schema) { source.Validate(schema, null); }
private void Push(TypeSchema typeSchema) { _currentSchema = typeSchema.Schema; _stack.Add(typeSchema); _resolver.LoadedSchemas.Add(typeSchema.Schema); }
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) { // resolved schema is not null but referencing member allows nulls // change resolved schema to allow nulls. hacky but what are ya gonna do? if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) { resolvedSchema.Type |= JsonSchemaType.Null; } if (required && resolvedSchema.Required != true) { resolvedSchema.Required = true; } return(resolvedSchema); } } // test for unresolved circular reference if (_stack.Any(tc => tc.Type == type)) { throw new 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.GetJsonContainerAttribute(type) as JsonArrayAttribute; bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems); Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List <JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false)); } break; case JsonContractType.Primitive: CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true)) { CurrentSchema.Enum = new List <JToken>(); EnumValues <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; case JsonContractType.Dynamic: case JsonContractType.Linq: CurrentSchema.Type = JsonSchemaType.Any; break; default: throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } return(Pop().Schema); }
private static void Combine(JsonSchemaModel model, JsonSchema schema) { JsonSchemaModel jsonSchemaModel1 = model; int num1; if (!model.Required) { bool?required = schema.Required; num1 = required.HasValue ? (required.GetValueOrDefault() ? 1 : 0) : 0; } else { num1 = 1; } jsonSchemaModel1.Required = num1 != 0; JsonSchemaModel jsonSchemaModel2 = model; int num2 = (int)model.Type; JsonSchemaType? type = schema.Type; int num3 = type.HasValue ? (int)type.GetValueOrDefault() : (int)sbyte.MaxValue; int num4 = num2 & num3; jsonSchemaModel2.Type = (JsonSchemaType)num4; model.MinimumLength = MathUtils.Max(model.MinimumLength, schema.MinimumLength); model.MaximumLength = MathUtils.Min(model.MaximumLength, schema.MaximumLength); model.DivisibleBy = MathUtils.Max(model.DivisibleBy, schema.DivisibleBy); model.Minimum = MathUtils.Max(model.Minimum, schema.Minimum); model.Maximum = MathUtils.Max(model.Maximum, schema.Maximum); JsonSchemaModel jsonSchemaModel3 = model; int num5; if (!model.ExclusiveMinimum) { bool?exclusiveMinimum = schema.ExclusiveMinimum; num5 = exclusiveMinimum.HasValue ? (exclusiveMinimum.GetValueOrDefault() ? 1 : 0) : 0; } else { num5 = 1; } jsonSchemaModel3.ExclusiveMinimum = num5 != 0; JsonSchemaModel jsonSchemaModel4 = model; int num6; if (!model.ExclusiveMaximum) { bool?exclusiveMaximum = schema.ExclusiveMaximum; num6 = exclusiveMaximum.HasValue ? (exclusiveMaximum.GetValueOrDefault() ? 1 : 0) : 0; } else { num6 = 1; } jsonSchemaModel4.ExclusiveMaximum = num6 != 0; 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 = (IList <JToken>) new List <JToken>(); } CollectionUtils.AddRangeDistinct <JToken>(model.Enum, (IEnumerable <JToken>)schema.Enum, (IEqualityComparer <JToken>) new JTokenEqualityComparer()); } JsonSchemaModel jsonSchemaModel5 = model; int num7 = (int)model.Disallow; JsonSchemaType? disallow = schema.Disallow; int num8 = disallow.HasValue ? (int)disallow.GetValueOrDefault() : 0; int num9 = num7 | num8; jsonSchemaModel5.Disallow = (JsonSchemaType)num9; if (schema.Pattern == null) { return; } if (model.Patterns == null) { model.Patterns = (IList <string>) new List <string>(); } CollectionUtils.AddDistinct <string>(model.Patterns, schema.Pattern); }
private void method_0(Class133 class133_0) { this.jsonSchema_0 = class133_0.JsonSchema_0; this.ilist_0.Add(class133_0); this.jsonSchemaResolver_0.LoadedSchemas.Add(class133_0.JsonSchema_0); }
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.OptionLabelPropertyName); _writer.WriteValue(option.Value); } _writer.WriteEndObject(); } _writer.WriteEndArray(); } if (schema.Disallow != null) { WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.Value); } if (schema.Extends != null) { _writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName); ReferenceOrWriteSchema(schema.Extends); } _writer.WriteEndObject(); }
private JsonSchema method_5(Type type_0, Required required_0, bool bool_0) { JsonConverter converter; Class134 class4 = new Class134 { type_0 = type_0 }; Class203.smethod_2(class4.type_0, "type"); string str = this.method_4(class4.type_0, false); string str2 = this.method_4(class4.type_0, true); if (!string.IsNullOrEmpty(str)) { JsonSchema schema = this.jsonSchemaResolver_0.GetSchema(str); if (schema != null) { if ((required_0 != Required.Always) && !smethod_0(schema.Type, JsonSchemaType.Null)) { schema.Type = ((JsonSchemaType)schema.Type) | JsonSchemaType.Null; } if (bool_0 && (schema.Required != true)) { schema.Required = true; } return(schema); } } if (this.ilist_0.Any <Class133>(new Func <Class133, bool>(class4.method_0))) { 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.".smethod_0(CultureInfo.InvariantCulture, class4.type_0)); } JsonContract contract = this.ContractResolver.ResolveContract(class4.type_0); if (((converter = contract.Converter) != null) || ((converter = contract.JsonConverter_0) != null)) { JsonSchema schema2 = converter.GetSchema(); if (schema2 != null) { return(schema2); } } this.method_0(new Class133(class4.type_0, new JsonSchema())); if (str2 != null) { this.JsonSchema_0.Id = str2; } if (bool_0) { this.JsonSchema_0.Required = true; } this.JsonSchema_0.Title = this.method_2(class4.type_0); this.JsonSchema_0.Description = this.method_3(class4.type_0); if (converter != null) { this.JsonSchema_0.Type = 0x7f; } else { switch (contract.enum15_0) { case Enum15.Object: this.JsonSchema_0.Type = new JsonSchemaType?(this.method_6(JsonSchemaType.Object, required_0)); this.JsonSchema_0.Id = this.method_4(class4.type_0, false); this.method_8(class4.type_0, (JsonObjectContract)contract); goto Label_04CD; case Enum15.Array: { this.JsonSchema_0.Type = new JsonSchemaType?(this.method_6(JsonSchemaType.Array, required_0)); this.JsonSchema_0.Id = this.method_4(class4.type_0, false); JsonArrayAttribute attribute = Class139.smethod_0(class4.type_0) as JsonArrayAttribute; bool flag = (attribute == null) || attribute.AllowNullItems; Type type = Class194.smethod_18(class4.type_0); if (type != null) { this.JsonSchema_0.Items = new List <JsonSchema>(); this.JsonSchema_0.Items.Add(this.method_5(type, !flag ? Required.Always : Required.Default, false)); } goto Label_04CD; } case Enum15.Primitive: this.JsonSchema_0.Type = new JsonSchemaType?(this.method_10(class4.type_0, required_0)); if (((((JsonSchemaType)this.JsonSchema_0.Type) == JsonSchemaType.Integer) && class4.type_0.smethod_7()) && !class4.type_0.IsDefined(typeof(FlagsAttribute), true)) { this.JsonSchema_0.Enum = new List <JToken>(); foreach (Class187 <long> class3 in Class186.smethod_2 <long>(class4.type_0)) { JToken item = JToken.FromObject(class3.Prop_0); this.JsonSchema_0.Enum.Add(item); } } goto Label_04CD; case Enum15.String: { JsonSchemaType type2 = !Class194.smethod_9(contract.UnderlyingType) ? JsonSchemaType.String : this.method_6(JsonSchemaType.String, required_0); this.JsonSchema_0.Type = new JsonSchemaType?(type2); goto Label_04CD; } case Enum15.Dictionary: Type type3; Type type4; this.JsonSchema_0.Type = new JsonSchemaType?(this.method_6(JsonSchemaType.Object, required_0)); Class194.smethod_19(class4.type_0, out type3, out type4); if ((type3 != null) && (this.ContractResolver.ResolveContract(type3).enum15_0 == Enum15.Primitive)) { this.JsonSchema_0.AdditionalProperties = this.method_5(type4, Required.Default, false); } goto Label_04CD; case Enum15.Dynamic: case Enum15.Linq: this.JsonSchema_0.Type = 0x7f; goto Label_04CD; case Enum15.Serializable: this.JsonSchema_0.Type = new JsonSchemaType?(this.method_6(JsonSchemaType.Object, required_0)); this.JsonSchema_0.Id = this.method_4(class4.type_0, false); this.method_9(class4.type_0, (JsonISerializableContract)contract); goto Label_04CD; } throw new JsonException("Unexpected contract type: {0}".smethod_0(CultureInfo.InvariantCulture, contract)); } Label_04CD: return(this.method_1().JsonSchema_0); }
public void WriteSchema(JsonSchema schema) { ValidationUtils.ArgumentNotNull(schema, "schema"); if (!this._resolver.LoadedSchemas.Contains(schema)) { this._resolver.LoadedSchemas.Add(schema); } this._writer.WriteStartObject(); this.WritePropertyIfNotNull(this._writer, "id", schema.Id); this.WritePropertyIfNotNull(this._writer, "title", schema.Title); this.WritePropertyIfNotNull(this._writer, "description", schema.Description); this.WritePropertyIfNotNull(this._writer, "required", schema.Required); this.WritePropertyIfNotNull(this._writer, "readonly", schema.ReadOnly); this.WritePropertyIfNotNull(this._writer, "hidden", schema.Hidden); this.WritePropertyIfNotNull(this._writer, "transient", schema.Transient); if (schema.Type.HasValue) { this.WriteType("type", this._writer, schema.Type.Value); } if (!schema.AllowAdditionalProperties) { this._writer.WritePropertyName("additionalProperties"); this._writer.WriteValue(schema.AllowAdditionalProperties); } else if (schema.AdditionalProperties != null) { this._writer.WritePropertyName("additionalProperties"); this.ReferenceOrWriteSchema(schema.AdditionalProperties); } this.WriteSchemaDictionaryIfNotNull(this._writer, "properties", schema.Properties); this.WriteSchemaDictionaryIfNotNull(this._writer, "patternProperties", schema.PatternProperties); this.WriteItems(schema); this.WritePropertyIfNotNull(this._writer, "minimum", schema.Minimum); this.WritePropertyIfNotNull(this._writer, "maximum", schema.Maximum); this.WritePropertyIfNotNull(this._writer, "exclusiveMinimum", schema.ExclusiveMinimum); this.WritePropertyIfNotNull(this._writer, "exclusiveMaximum", schema.ExclusiveMaximum); this.WritePropertyIfNotNull(this._writer, "minLength", schema.MinimumLength); this.WritePropertyIfNotNull(this._writer, "maxLength", schema.MaximumLength); this.WritePropertyIfNotNull(this._writer, "minItems", schema.MinimumItems); this.WritePropertyIfNotNull(this._writer, "maxItems", schema.MaximumItems); this.WritePropertyIfNotNull(this._writer, "divisibleBy", schema.DivisibleBy); this.WritePropertyIfNotNull(this._writer, "format", schema.Format); this.WritePropertyIfNotNull(this._writer, "pattern", schema.Pattern); if (schema.Enum != null) { this._writer.WritePropertyName("enum"); this._writer.WriteStartArray(); foreach (JToken @enum in schema.Enum) { @enum.WriteTo(this._writer, new JsonConverter[0]); } this._writer.WriteEndArray(); } if (schema.Default != null) { this._writer.WritePropertyName("default"); schema.Default.WriteTo(this._writer, new JsonConverter[0]); } if (schema.Options != null) { this._writer.WritePropertyName("options"); this._writer.WriteStartArray(); foreach (KeyValuePair <JToken, string> option in schema.Options) { this._writer.WriteStartObject(); this._writer.WritePropertyName("value"); option.Key.WriteTo(this._writer, new JsonConverter[0]); if (option.Value != null) { this._writer.WritePropertyName("label"); this._writer.WriteValue(option.Value); } this._writer.WriteEndObject(); } this._writer.WriteEndArray(); } if (schema.Disallow.HasValue) { this.WriteType("disallow", this._writer, schema.Disallow.Value); } if (schema.Extends != null) { this._writer.WritePropertyName("extends"); this.ReferenceOrWriteSchema(schema.Extends); } this._writer.WriteEndObject(); }
private void Push(JsonSchema value) { this._currentSchema = value; this._stack.Add(value); this._resolver.LoadedSchemas.Add(value); }
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull((object)type, "type"); string typeId1 = this.GetTypeId(type, false); string typeId2 = this.GetTypeId(type, true); if (!string.IsNullOrEmpty(typeId1)) { JsonSchema schema = this._resolver.GetSchema(typeId1); if (schema != null) { if (valueRequired != Required.Always && !JsonSchemaGenerator.HasFlag(schema.Type, JsonSchemaType.Null)) { JsonSchema jsonSchema = schema; JsonSchemaType?type1 = jsonSchema.Type; JsonSchemaType?nullable = type1.HasValue ? new JsonSchemaType?(type1.GetValueOrDefault() | JsonSchemaType.Null) : new JsonSchemaType?(); jsonSchema.Type = nullable; } if (required) { bool?required1 = schema.Required; if ((!required1.GetValueOrDefault() ? 1 : (!required1.HasValue ? 1 : 0)) != 0) { schema.Required = new bool?(true); } } return(schema); } } if (Enumerable.Any <JsonSchemaGenerator.TypeSchema>((IEnumerable <JsonSchemaGenerator.TypeSchema>) this._stack, (Func <JsonSchemaGenerator.TypeSchema, bool>)(tc => tc.Type == type))) { throw new JsonException(StringUtils.FormatWith("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.", (IFormatProvider)CultureInfo.InvariantCulture, (object)type)); } JsonContract jsonContract = this.ContractResolver.ResolveContract(type); JsonConverter jsonConverter; if ((jsonConverter = jsonContract.Converter) != null || (jsonConverter = jsonContract.InternalConverter) != null) { JsonSchema schema = jsonConverter.GetSchema(); if (schema != null) { return(schema); } } this.Push(new JsonSchemaGenerator.TypeSchema(type, new JsonSchema())); if (typeId2 != null) { this.CurrentSchema.Id = typeId2; } if (required) { this.CurrentSchema.Required = new bool?(true); } this.CurrentSchema.Title = this.GetTitle(type); this.CurrentSchema.Description = this.GetDescription(type); if (jsonConverter != null) { this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any); } else { switch (jsonContract.ContractType) { case JsonContractType.Object: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); this.GenerateObjectSchema(type, (JsonObjectContract)jsonContract); break; case JsonContractType.Array: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); JsonArrayAttribute jsonArrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute; bool flag = jsonArrayAttribute == null || jsonArrayAttribute.AllowNullItems; Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { this.CurrentSchema.Items = (IList <JsonSchema>) new List <JsonSchema>(); this.CurrentSchema.Items.Add(this.GenerateInternal(collectionItemType, !flag ? Required.Always : Required.Default, false)); break; } else { break; } case JsonContractType.Primitive: this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired)); JsonSchemaType?type2 = this.CurrentSchema.Type; if ((type2.GetValueOrDefault() != JsonSchemaType.Integer ? 0 : (type2.HasValue ? 1 : 0)) != 0 && TypeExtensions.IsEnum(type) && !type.IsDefined(typeof(FlagsAttribute), true)) { this.CurrentSchema.Enum = (IList <JToken>) new List <JToken>(); this.CurrentSchema.Options = (IDictionary <JToken, string>) new Dictionary <JToken, string>(); using (IEnumerator <EnumValue <long> > enumerator = EnumUtils.GetNamesAndValues <long>(type).GetEnumerator()) { while (enumerator.MoveNext()) { EnumValue <long> current = enumerator.Current; JToken key = JToken.FromObject((object)current.Value); this.CurrentSchema.Enum.Add(key); this.CurrentSchema.Options.Add(key, current.Name); } break; } } else { break; } case JsonContractType.String: this.CurrentSchema.Type = new JsonSchemaType?(!ReflectionUtils.IsNullable(jsonContract.UnderlyingType) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired)); break; case JsonContractType.Dictionary: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); if (keyType != null && ConvertUtils.IsConvertible(keyType)) { this.CurrentSchema.AdditionalProperties = this.GenerateInternal(valueType, Required.Default, false); break; } else { break; } case JsonContractType.Serializable: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); this.GenerateISerializableContract(type, (JsonISerializableContract)jsonContract); break; case JsonContractType.Linq: this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any); break; default: throw new JsonException(StringUtils.FormatWith("Unexpected contract type: {0}", (IFormatProvider)CultureInfo.InvariantCulture, (object)jsonContract)); } } return(this.Pop().Schema); }
// Token: 0x060013CD RID: 5069 RVA: 0x00068C14 File Offset: 0x00066E14 private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string typeId = this.GetTypeId(type, false); string typeId2 = this.GetTypeId(type, true); if (!StringUtils.IsNullOrEmpty(typeId)) { JsonSchema schema = this._resolver.GetSchema(typeId); if (schema != null) { if (valueRequired != Required.Always && !JsonSchemaGenerator.HasFlag(schema.Type, JsonSchemaType.Null)) { schema.Type |= JsonSchemaType.Null; } if (required) { bool?required2 = schema.Required; if (!(required2.GetValueOrDefault() & required2 != null)) { schema.Required = new bool?(true); } } return(schema); } } if (this._stack.Any((JsonSchemaGenerator.TypeSchema 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 jsonContract = this.ContractResolver.ResolveContract(type); bool flag = (jsonContract.Converter ?? jsonContract.InternalConverter) != null; this.Push(new JsonSchemaGenerator.TypeSchema(type, new JsonSchema())); if (typeId2 != null) { this.CurrentSchema.Id = typeId2; } if (required) { this.CurrentSchema.Required = new bool?(true); } this.CurrentSchema.Title = this.GetTitle(type); this.CurrentSchema.Description = this.GetDescription(type); if (flag) { this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any); } else { switch (jsonContract.ContractType) { case JsonContractType.Object: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); this.GenerateObjectSchema(type, (JsonObjectContract)jsonContract); break; case JsonContractType.Array: { this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); JsonArrayAttribute cachedAttribute = JsonTypeReflector.GetCachedAttribute <JsonArrayAttribute>(type); bool flag2 = cachedAttribute == null || cachedAttribute.AllowNullItems; Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { this.CurrentSchema.Items = new List <JsonSchema>(); this.CurrentSchema.Items.Add(this.GenerateInternal(collectionItemType, (!flag2) ? Required.Always : Required.Default, false)); } break; } case JsonContractType.Primitive: { this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired)); JsonSchemaType?type2 = this.CurrentSchema.Type; if ((type2.GetValueOrDefault() == JsonSchemaType.Integer & type2 != null) && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true)) { this.CurrentSchema.Enum = new List <JToken>(); EnumInfo enumValuesAndNames = EnumUtils.GetEnumValuesAndNames(type); for (int i = 0; i < enumValuesAndNames.Names.Length; i++) { ulong value = enumValuesAndNames.Values[i]; JToken item = JToken.FromObject(Enum.ToObject(type, value)); this.CurrentSchema.Enum.Add(item); } } break; } case JsonContractType.String: { JsonSchemaType value2 = (!ReflectionUtils.IsNullable(jsonContract.UnderlyingType)) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired); this.CurrentSchema.Type = new JsonSchemaType?(value2); break; } case JsonContractType.Dictionary: { this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); Type type3; Type type4; ReflectionUtils.GetDictionaryKeyValueTypes(type, out type3, out type4); if (type3 != null && this.ContractResolver.ResolveContract(type3).ContractType == JsonContractType.Primitive) { this.CurrentSchema.AdditionalProperties = this.GenerateInternal(type4, Required.Default, false); } break; } case JsonContractType.Dynamic: case JsonContractType.Linq: this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any); break; case JsonContractType.Serializable: this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired)); this.CurrentSchema.Id = this.GetTypeId(type, false); this.GenerateISerializableContract(type, (JsonISerializableContract)jsonContract); break; default: throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContract)); } } return(this.Pop().Schema); }