/// <summary> /// Gets the Google type for the specified path is valid for this schema. /// </summary> /// <param name="schema">JSON Schema.</param> /// <param name="flattenedPath">Flattened state path.</param> /// <returns>The <see cref="GoogleType"/> for the specified path.</returns> public static GoogleType GetGoogleTypeForFlattenedPath(this NJsonSchema.JsonSchema schema, string flattenedPath) { var foundSchemas = schema.GetByFlattenedPath(flattenedPath); if (!foundSchemas.Any()) { return(GoogleType.Unknown); } foreach (var foundSchema in foundSchemas) { switch (foundSchema.Type) { case NJsonSchema.JsonObjectType.Integer: case NJsonSchema.JsonObjectType.Number: return(GoogleType.Numeric); case NJsonSchema.JsonObjectType.Boolean: return(GoogleType.Bool); case NJsonSchema.JsonObjectType.String: return(GoogleType.String); } } return(GoogleType.Unknown); }
private static string[] _GetProperyNames(JSONSCHEMA schema) { return(schema .Properties .Values .Select(item => item.Name) .ToArray()); }
static NJsonSchema.JsonReferenceResolver _Resolver(JSONSCHEMA schema, string basePath) { var generator = new NJsonSchema.Generation.JsonSchemaGeneratorSettings(); var solver = new NJsonSchema.JsonSchemaAppender(schema, generator.TypeNameGenerator); return(new MyReferenceResolver(solver)); }
private static bool _IsClass(JSONSCHEMA schema) { if (schema.Type != NJsonSchema.JsonObjectType.Object) { return(false); } return(!string.IsNullOrWhiteSpace(schema.Title)); }
private static string[] _GetInheritedPropertyNames(JSONSCHEMA schema) { if (schema?.InheritedSchema == null) { return(Enumerable.Empty <string>().ToArray()); } return(_GetInheritedPropertyNames(schema.InheritedSchema) .Concat(_GetProperyNames(schema.InheritedSchema)) .ToArray()); }
JSONSchemaFromJSON ( string json ) { NJsonSchema.JsonSchema schema = await NJsonSchema.JsonSchema.FromJsonAsync(json); string schemaData = schema.ToJson(); return(schema); }
private static bool _IsDictionary(JSONSCHEMA schema) { // if (schema.Type != NJsonSchema.JsonObjectType.Object) return false; if (schema.AdditionalPropertiesSchema != null) { return(true); } if (schema.AllowAdditionalProperties == false && schema.PatternProperties.Any()) { return(true); } return(false); }
static JSONSCHEMA LoadSchema(string filePath) { // https://blogs.msdn.microsoft.com/benjaminperkins/2017/03/08/how-to-call-an-async-method-from-a-console-app-main-method/ if (!System.IO.File.Exists(filePath)) { throw new System.IO.FileNotFoundException(nameof(filePath), filePath); } return(JSONSCHEMA .FromFileAsync(filePath, s => _Resolver(s, filePath)) .ConfigureAwait(false) .GetAwaiter() .GetResult()); }
/// <summary> /// Gets the Google type for the specified path is valid for this schema. /// </summary> /// <param name="schema">JSON Schema.</param> /// <param name="flattenedPath">Flattened state path.</param> /// <returns>The <see cref="GoogleType"/> for the specified path.</returns> public static ICollection <object> GetEnumValuesForFlattenedPath(this NJsonSchema.JsonSchema schema, string flattenedPath) { var foundSchemas = schema.GetByFlattenedPath(flattenedPath); var result = new List <object>(); foreach (var foundSchema in foundSchemas) { if (foundSchema.IsEnumeration) { result.AddRange(foundSchema.Enumeration); } } return(result.Any() ? result : null); }
static async Task <NJsonSchema.JsonSchema> GetSchema(mmria.common.metadata.app p_app) { //https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Schema_JsonSchema.htm var schema = new NJsonSchema.JsonSchema(); schema.Type = NJsonSchema.JsonObjectType.Object; schema.Title = "mmria_case"; schema.Description = "Here is a case for your ...!"; schema.SchemaVersion = "http://json-schema.org/draft-06/schema#"; schema.Properties.Add("_id", new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.String }); //schema.Properties.Add("name", new NJsonSchema.JsonSchemaProperty(){ Type = NJsonSchema.JsonObjectType.String}); //schema.Properties.Add("prompt", new NJsonSchema.JsonSchemaProperty(){ Type = NJsonSchema.JsonObjectType.String}); try { foreach (var child in p_app.lookup) { Set_LookUp(schema.Definitions, child); } } catch (Exception ex) { System.Console.Write($"Set_LookUp Exception: {ex}"); } try { foreach (var child in p_app.children) { await GetSchema(schema.Definitions, schema, child); } } catch (Exception ex) { System.Console.Write($"GetSchema Exception: {ex}"); } return(schema); }
private static JSONSCHEMA _GetDictionaryValue(JSONSCHEMA schema) { if (schema.AdditionalPropertiesSchema != null) { return(schema.AdditionalPropertiesSchema); } if (schema.AllowAdditionalProperties == false && schema.PatternProperties.Any()) { var valueTypes = schema.PatternProperties.Values.ToArray(); if (valueTypes.Length == 1) { return(valueTypes.First()); } } throw new NotImplementedException(); }
private static bool _IsBlittableType(JSONSCHEMA schema) { if (schema == null) { return(false); } if (schema.Type == NJsonSchema.JsonObjectType.Boolean) { return(true); } if (schema.Type == NJsonSchema.JsonObjectType.Number) { return(true); } if (schema.Type == NJsonSchema.JsonObjectType.Integer) { return(true); } return(false); }
private static bool _IsEnumeration(JSONSCHEMA schema) { if (schema.Type != NJsonSchema.JsonObjectType.None) { return(false); } if (schema.IsArray || schema.IsDictionary) { return(false); } if (schema.AnyOf.Count == 0) { return(false); } // if (!schema.IsEnumeration) return false; // useless return(true); }
CodeFromJSONSchema ( NJsonSchema.JsonSchema json_schema ) { NJsonSchema.CodeGeneration.CSharp.CSharpGenerator generator; NJsonSchema.CodeGeneration.CSharp.CSharpGeneratorSettings generator_settings; generator_settings = new NJsonSchema.CodeGeneration.CSharp.CSharpGeneratorSettings() { ClassStyle = NJsonSchema.CodeGeneration.CSharp.CSharpClassStyle.Poco, JsonLibrary = NJsonSchema.CodeGeneration.CSharp.CSharpJsonLibrary.SystemTextJson }; generator = new NJsonSchema.CodeGeneration.CSharp.CSharpGenerator ( json_schema, generator_settings ); string code = generator.GenerateFile(); return(code); }
public static int ValidateJSONAlternative(AasValidationRecordList recs, Stream jsonContent) { // see: https://github.com/RicoSuter/NJsonSchema/wiki/JsonSchemaValidator var newRecs = new AasValidationRecordList(); // access if (recs == null || jsonContent == null) { return(-1); } // Load the schema files // right now: exactly ONE schema file var files = GetSchemaResources(SerializationFormat.JSON); if (files == null || files.Length != 1) { return(-1); } NJsonSchema.JsonSchema schema = null; try { Assembly myAssembly = Assembly.GetExecutingAssembly(); foreach (var schemaFn in files) { using (Stream schemaStream = myAssembly.GetManifestResourceStream(schemaFn)) { using (var streamReader = new StreamReader(schemaStream)) { var allTxt = streamReader.ReadToEnd(); schema = NJsonSchema.JsonSchema.FromJsonAsync(allTxt).GetAwaiter().GetResult(); break; } } } } catch (Exception ex) { throw new FileNotFoundException("ValidateJSON: Error loading schema: " + ex.Message); } if (schema == null) { throw new FileNotFoundException("ValidateJSON: Schema not found properly."); } // create validator var validator = new NJsonSchema.Validation.JsonSchemaValidator(); // load the JSON content string jsonTxt = null; try { using (var streamReader = new StreamReader(jsonContent)) { jsonTxt = streamReader.ReadToEnd(); } } catch (Exception ex) { throw new InvalidOperationException("ValidateJSON: Error loading JSON content: " + ex.Message); } if (jsonTxt == null || jsonTxt == "") { throw new InvalidOperationException("ValidateJSON: Error loading JSON content gave null."); } // validate ICollection <NJsonSchema.Validation.ValidationError> errors; try { errors = validator.Validate(jsonTxt, schema); } catch (Exception ex) { throw new InvalidOperationException("ValidateJSON: Error when validating: " + ex.Message); } // re-format messages if (errors != null) { foreach (var ve in errors) { var msg = ("" + ve.ToString()); msg = Regex.Replace(msg, @"\s+", " "); newRecs.Add(new AasValidationRecord(AasValidationSeverity.Serialization, null, $"JSON: {ve.LineNumber,5},{ve.LinePosition:3}: {msg}")); } } // result recs.AddRange(newRecs); return(newRecs.Count); }
/// <summary> /// Validates if the specified path is valid for this schema. /// </summary> /// <param name="schema">JSON Schema.</param> /// <param name="flattenedPath">Flattened state path.</param> /// <returns><c>true</c> if path is valid for schema, otherwise <c>false</c>.</returns> public static bool FlattenedPathExists(this NJsonSchema.JsonSchema schema, string flattenedPath) { return(schema.GetByFlattenedPath(flattenedPath).Any()); }
/// <summary> /// Gets the schema item for the specified path for this schema. /// </summary> /// <param name="schema">JSON Schema.</param> /// <param name="flattenedPath">Flattened state path.</param> /// <returns>A list of matching <see cref="NJsonSchema.JsonSchema"/> for the specified path.</returns> public static IList <NJsonSchema.JsonSchema> GetByFlattenedPath(this NJsonSchema.JsonSchema schema, string flattenedPath) { const string delimiter = "."; var paths = flattenedPath?.Split(delimiter, 2); var currentPathFragment = paths?[0]; var remainingPathFragment = paths != null && paths.Length == 2 ? paths[1] : null; switch (schema.Type) { case NJsonSchema.JsonObjectType.Object: case NJsonSchema.JsonObjectType.None: // Treat unspecified types as possible subschemas if (currentPathFragment == null) { return(new List <NJsonSchema.JsonSchema>()); } var objectResults = new List <NJsonSchema.JsonSchema>(); if (schema.Properties != null && schema.Properties.ContainsKey(currentPathFragment)) { // Recursive traversal of objects objectResults.AddRange(GetByFlattenedPath(schema.Properties[currentPathFragment], remainingPathFragment)); } if (schema.AnyOf != null) { foreach (var propertySchema in schema.AnyOf) { // Unwrap and validate each as a possibility objectResults.AddRange(GetByFlattenedPath(propertySchema, flattenedPath)); } } if (schema.OneOf != null) { foreach (var propertySchema in schema.OneOf) { // Unwrap and validate each as a possibility objectResults.AddRange(GetByFlattenedPath(propertySchema, flattenedPath)); } } if (schema.AdditionalPropertiesSchema != null) { // Use the additional property schema, if available objectResults.AddRange(GetByFlattenedPath(schema.AdditionalPropertiesSchema, flattenedPath)); } if (objectResults.Any()) { return(objectResults); } break; case NJsonSchema.JsonObjectType.Array: if (currentPathFragment == null) { return(new List <NJsonSchema.JsonSchema>()); } if (schema.Item != null) { if (Regex.IsMatch(currentPathFragment, @"^\[\d+\]$")) { // Unwrap array item return(GetByFlattenedPath(schema.Item, remainingPathFragment)); } } else { var arrayItemResult = new List <NJsonSchema.JsonSchema>(); foreach (var branch in schema.Items) { if (Regex.IsMatch(currentPathFragment, @"^\[\d+\]$")) { // Unwrap array item arrayItemResult.AddRange(GetByFlattenedPath(branch, remainingPathFragment)); } } if (arrayItemResult.Any()) { return(arrayItemResult); } } break; case NJsonSchema.JsonObjectType.Integer: case NJsonSchema.JsonObjectType.Number: case NJsonSchema.JsonObjectType.Boolean: case NJsonSchema.JsonObjectType.String: // Matching leaf node found return(new List <NJsonSchema.JsonSchema> { schema }); } return(new List <NJsonSchema.JsonSchema>()); }
static async Task <NJsonSchema.JsonSchema> GetSchema(IDictionary <string, NJsonSchema.JsonSchema> p_lookup, NJsonSchema.JsonSchema p_parent, mmria.common.metadata.node p_node) { //https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Schema_JsonSchema.htm /* * var schema = new NJsonSchema.JsonSchema(); * * schema.Type = NJsonSchema.JsonObjectType.Object; * schema.Title = "mmria_case"; * schema.Description = "Here is a case for your ...!"; * * schema.SchemaVersion = "http://json-schema.org/draft-06/schema#"; */ NJsonSchema.JsonSchemaProperty property = null; NJsonSchema.JsonSchemaProperty property_list = null; //schema.Properties.Add("name", new NJsonSchema.JsonSchemaProperty(){ Type = NJsonSchema.JsonObjectType.String}); //schema.Properties.Add("prompt", new NJsonSchema.JsonSchemaProperty(){ Type = NJsonSchema.JsonObjectType.String}); try { switch (p_node.type.ToLower()) { case "form": if (p_node.type.ToLower() == "form" && p_node.cardinality == "*") { property = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.Object }; foreach (var child in p_node.children) { await GetSchema(p_lookup, property, child); } p_lookup.Add(p_node.name + "_type", property); property_list = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.Array, Item = p_lookup[p_node.name + "_type"] }; //property_list.Properties..Items.Allof(property); p_parent.Properties.Add(p_node.name + "_form", property_list); } else { property = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.Object }; foreach (var child in p_node.children) { await GetSchema(p_lookup, property, child); } p_parent.Properties.Add(p_node.name, property); } break; case "grid": property = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.Object }; foreach (var child in p_node.children) { await GetSchema(p_lookup, property, child); } var number = -1; var key = p_node.name + "_row"; var suffix = ""; if (p_lookup.ContainsKey(key)) { number = p_lookup.Count; suffix = number.ToString(); } var property_name = key + suffix; p_lookup.Add(property_name, property); property_list = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.Array, Item = p_lookup[property_name] }; var grid_name = p_node.name + "_grid" + suffix; p_parent.Properties.Add(grid_name, property_list); break; case "app": case "group": property = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.Object }; p_parent.Properties.Add(p_node.name, property); foreach (var child in p_node.children) { await GetSchema(p_lookup, property, child); } break; case "textarea": case "hidden": case "string": var string_property = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.String }; if (p_node.default_value != null) { string_property.Default = p_node.default_value; } if (p_node.is_required.HasValue && p_node.is_required.Value) { string_property.IsRequired = true; } p_parent.Properties.Add(p_node.name, string_property); break; case "datetime": case "date": case "time": var date_property = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.String, Format = "date-time" }; if (p_node.is_required.HasValue && p_node.is_required.Value) { date_property.IsRequired = true; } p_parent.Properties.Add(p_node.name, date_property); break; case "number": var number_property = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.Number }; if (p_node.default_value != null) { decimal decimal_value; if (decimal.TryParse(p_node.default_value, out decimal_value)) { number_property.Default = decimal_value; } } if (p_node.is_required.HasValue && p_node.is_required.Value) { number_property.IsRequired = true; } if (p_node.min_value != null) { decimal number_value; if (decimal.TryParse(p_node.min_value, out number_value)) { number_property.Minimum = number_value; } } if (p_node.max_value != null) { decimal number_value; if (decimal.TryParse(p_node.max_value, out number_value)) { number_property.Maximum = number_value; } } p_parent.Properties.Add(p_node.name, number_property); break; case "boolean": var boolean_property = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.Boolean }; if (p_node.is_required.HasValue && p_node.is_required.Value) { boolean_property.IsRequired = true; } if (p_node.default_value != null) { bool bool_value; if (bool.TryParse(p_node.default_value, out bool_value)) { boolean_property.Default = bool_value; } } p_parent.Properties.Add(p_node.name, boolean_property); break; case "list": if (p_node.is_multiselect.HasValue && p_node.is_multiselect.Value == true) { property = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.Array }; p_parent.Properties.Add(p_node.name, property); if (!string.IsNullOrWhiteSpace(p_node.path_reference)) { property.Reference = p_lookup[p_node.path_reference.Replace("lookup/", "")]; //p_parent.Properties.Add(p_node.name, property); } else { foreach (var value in p_node.values) { property.EnumerationNames.Add(value.value); } } } else { property = new NJsonSchema.JsonSchemaProperty() { Type = NJsonSchema.JsonObjectType.String }; p_parent.Properties.Add(p_node.name, property); if (!string.IsNullOrWhiteSpace(p_node.path_reference)) { property.Reference = p_lookup[p_node.path_reference.Replace("lookup/", "")]; //p_parent.Properties.Add(p_node.name, property); } else { foreach (var value in p_node.values) { property.EnumerationNames.Add(value.value); } } } break; case "button": case "chart": case "label": break; default: System.Console.Write($"Convert.cs.GetSchema.switch.Missing: {p_node.type}"); break; } } catch (Exception ex) { System.Console.Write($"GetSchemaGetSchema(p_parent, p_node) Exception: {ex}"); } return(p_parent); }
private static SchemaType _UseType(this SchemaType.Context ctx, JSONSCHEMA schema, bool isRequired = true) { if (ctx == null) { throw new ArgumentNullException(nameof(ctx)); } if (schema == null) { throw new ArgumentNullException(nameof(schema)); } if (schema is NJsonSchema.JsonSchemaProperty prop) { // System.Diagnostics.Debug.Assert(prop.Name != "scene"); isRequired &= prop.IsRequired; } if (_IsStringType(schema)) { return(ctx.UseString()); } if (_IsBlittableType(schema)) { bool isNullable = !isRequired; if (schema.Type == NJsonSchema.JsonObjectType.Integer) { return(ctx.UseBlittable(typeof(Int32).GetTypeInfo(), isNullable)); } if (schema.Type == NJsonSchema.JsonObjectType.Number) { return(ctx.UseBlittable(typeof(Double).GetTypeInfo(), isNullable)); } if (schema.Type == NJsonSchema.JsonObjectType.Boolean) { return(ctx.UseBlittable(typeof(Boolean).GetTypeInfo(), isNullable)); } throw new NotImplementedException(); } if (schema.HasReference) { return(ctx._UseType(schema.ActualTypeSchema, isRequired)); // we could have our own ref } if (schema.IsArray) { return(ctx.UseArray(ctx._UseType(schema.Item.ActualSchema))); } if (_IsEnumeration(schema)) { if (schema is NJsonSchema.JsonSchemaProperty property) { bool isNullable = !isRequired; var dict = new Dictionary <string, Int64>(); foreach (var v in property.AnyOf) { var val = v.Enumeration.FirstOrDefault(); var key = v.Description; if (val is String) { key = (string)val; val = (Int64)0; } if (string.IsNullOrWhiteSpace(key)) { continue; } dict[key] = (Int64)val; } // JSon Schema AnyOf enumerations are basically anonymous, so we create // a "shared name" with a concatenation of all the values: var name = string.Join("-", dict.Keys.OrderBy(item => item)); var etype = ctx.UseEnum(name, isNullable); etype.Description = schema.Description; foreach (var kvp in dict) { etype.SetValue(kvp.Key, (int)kvp.Value); } if (dict.Values.Distinct().Count() > 1) { etype.UseIntegers = true; } return(etype); } throw new NotImplementedException(); } if (_IsDictionary(schema)) { var key = ctx.UseString(); var val = ctx._UseType(_GetDictionaryValue(schema)); return(ctx.UseDictionary(key, val)); } if (_IsClass(schema)) { var classDecl = ctx.UseClass(schema.Title); classDecl.Description = schema.Description; // process base class if (schema.InheritedSchema != null) { classDecl.BaseClass = ctx._UseType(schema.InheritedSchema) as ClassType; } // filter declared properties var keys = _GetProperyNames(schema); if (schema.InheritedSchema != null) // filter our parent properties { var baseKeys = _GetInheritedPropertyNames(schema).ToArray(); keys = keys.Except(baseKeys).ToArray(); } // process declared properties var props = keys.Select(key => schema.Properties.Values.FirstOrDefault(item => item.Name == key)); var required = schema.RequiredProperties; // System.Diagnostics.Debug.Assert(schema.Title != "Buffer View"); foreach (var p in props) { var field = classDecl.UseField(p.Name); field.Description = p.Description; field.FieldType = ctx._UseType(p, required.Contains(p.Name)); field.MinimumValue = p.Minimum; field.MaximumValue = p.Maximum; field.DefaultValue = p.Default; field.MinItems = p.MinItems; field.MaxItems = p.MaxItems; } return(classDecl); } if (schema.Type == NJsonSchema.JsonObjectType.Object) { return(ctx.UseAnyType()); } if (schema.Type == NJsonSchema.JsonObjectType.None) { return(ctx.UseAnyType()); } throw new NotImplementedException(); }
private static bool _IsStringType(JSONSCHEMA schema) { return(schema.Type == NJsonSchema.JsonObjectType.String); }