public void When_discriminator_object_is_set_then_schema_is_correctly_serialized() { //// Arrange var childSchema = new JsonSchema4 { Type = JsonObjectType.Object, }; var schema = new JsonSchema4(); schema.Definitions["Foo"] = childSchema; schema.DiscriminatorObject = new OpenApiDiscriminator { PropertyName = "discr", Mapping = { { "Bar", new JsonSchema4 { Reference = childSchema } } } }; //// Act JsonSchemaSerializationContext.CurrentSchemaType = SchemaType.Swagger2; // will be ignored var json = schema.ToJson(); //// Assert Assert.Contains(@"""propertyName"": ""discr""", json); Assert.Contains(@"""Bar""", json); Assert.Contains(@"""$ref"": ""#/definitions/Foo""", json); }
public static async Task RestTest(string url) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json")); client.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter"); Task <string> stringTask = client.GetStringAsync(url); String json = await stringTask; // https://www.newtonsoft.com/json // https://github.com/RSuter/NJsonSchema JToken parsedJson = JToken.Parse(json); string beautified = parsedJson.ToString(Formatting.Indented); Debug.WriteLine("--------------------------------------------------"); Debug.WriteLine(beautified); JsonSchema4 jsonSchema = JsonSchema4.FromSampleJson(beautified); string beautifiedSchema = jsonSchema.ToJson(); Debug.WriteLine("--------------------------------------------------"); Debug.WriteLine(beautifiedSchema); CSharpGenerator generator = new CSharpGenerator(jsonSchema); string file = generator.GenerateFile(); Debug.WriteLine("--------------------------------------------------"); Debug.WriteLine(file); }
public static JSchema GenerateSchemaForClass <T>() { //Name: NJsonSchema for .NET (works with JSON.NET) //Owner: Rico Suter //Purpose: Generates json schemas from .NET classes; unlike JSON.NET, can generate an unlimited number. JsonSchema4 schema = null; try { schema = JsonSchema4.FromType <T>(); //generate json schema from .NET class } catch (Exception ex) { Console.WriteLine(ex); } //Name: Json.NET //Owner: James Newton-King //Purpose: format json schema into json //History: replaces JsonSchema, which is deprecated (may need to bring back if JSchema doesn't allow unlimited use) JSchema schemaData = null; try { schemaData = JSchema.Parse(schema.ToJson()); } catch (Exception ex) { Console.WriteLine(ex); } return(schemaData); }
public DataValidationReport(JsonSchema4 schema, int totalEntities, int totalProperties) { EntityReports = new EntityReportCollection(); Schema = schema.ToJson(); TotalRecordsEvaluated = totalEntities; TotalFieldsEvaluated = totalProperties; }
/// <summary>Converts the JSON Schema to YAML.</summary> /// <returns>The YAML string.</returns> public static string ToYaml(this JsonSchema4 document) { var json = document.ToJson(); var expConverter = new ExpandoObjectConverter(); dynamic deserializedObject = JsonConvert.DeserializeObject <ExpandoObject>(json, expConverter); var serializer = new Serializer(); return(serializer.Serialize(deserializedObject)); }
public void When_setting_single_type_then_it_should_be_serialized_correctly() { //// Arrange var schema = new JsonSchema4(); //// Act schema.Type = JsonObjectType.Integer; var data = schema.ToJson(); //// Assert Assert.IsTrue(data.Contains(@"""type"": ""integer""")); }
public void When_discriminator_is_set_then_discriminator_object_is_created() { //// Arrange var schema = new JsonSchema4(); schema.Discriminator = "discr"; //// Act var json = schema.ToJson(); //// Assert Assert.Contains(@"""discr""", json); }
/// <summary> /// Create a json schema from all discovered config object types. /// </summary> /// <returns>The json schema as a string.</returns> public async Task <String> CreateSchema() { var settings = new JsonSchemaGeneratorSettings() { FlattenInheritanceHierarchy = true, DefaultEnumHandling = EnumHandling.String }; var generator = new JsonSchemaGenerator(settings); var mergeSettings = new JsonMergeSettings() { MergeArrayHandling = MergeArrayHandling.Union }; var schema = new JsonSchema4(); foreach (var itemKey in configObjects.Keys) { var property = new JsonProperty(); JObject itemSchema = new JObject(); foreach (var item in configObjects[itemKey]) { if (item != typeof(Object)) { var jsonSchema = await generator.GenerateAsync(item); var jObjSchema = JObject.Parse(jsonSchema.ToJson()); jObjSchema["$schema"]?.Parent?.Remove(); //Remove any $schema properties itemSchema.Merge(jObjSchema, mergeSettings); } else { //If the type is ever object, set the type to object and stop itemSchema = new JObject(); property = new JsonProperty() { Type = JsonObjectType.Null | JsonObjectType.Object }; break; } } schema.Properties.Add(itemKey, property); if (itemSchema.Count > 0) { var jsonSchema = await JsonSchema4.FromJsonAsync(itemSchema.ToString()); property.Reference = jsonSchema; schema.Definitions.Add(itemKey, jsonSchema); } } return(schema.ToJson()); }
public static void WriteSchema(string sampleJson, FileInfo outputSchema) { Directory.CreateDirectory(outputSchema.DirectoryName); try { JsonSchema4 schema = JsonSchema4.FromSampleJson(sampleJson); File.WriteAllText(outputSchema.FullName, schema.ToJson()); } catch (Exception exception) { Console.WriteLine(exception); throw; } }
public void When_setting_multiple_type_then_it_should_be_serialized_correctly() { //// Arrange var schema = new JsonSchema4(); //// Act schema.Type = JsonObjectType.Integer | JsonObjectType.Object; var data = schema.ToJson(); //// Assert Assert.Contains(@" ""type"": [ ""integer"", ""object"" ]", data); }
public void When_creating_schema_without_setting_properties_then_it_is_empty() { //// Arrange var schema = new JsonSchema4(); //// Act var data = schema.ToJson(); //// Assert Assert.AreEqual( @"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"" }", data); Assert.IsTrue(schema.IsAnyType); }
public async Task When_object_is_in_external_file_then_path_should_be_built_correctly() { //// Arrange var schemaToReference = new JsonSchema4 { DocumentPath = "some_schema.json" }; var referencingSchema = new JsonSchema4 { DocumentPath = "other_schema.json", SchemaReference = schemaToReference }; //// Act var result = referencingSchema.ToJson(); //// Assert Assert.IsTrue(result.Contains("some_schema.json#")); }
public void When_schema_has_extension_data_property_then_property_is_in_serialized_json() { //// Arrange var schema = new JsonSchema4(); schema.ExtensionData = new Dictionary <string, object> { { "Test", 123 } }; //// Act var json = schema.ToJson(); //// Assert Assert.Contains(@"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""Test"": 123 }", json); }
public void When_schema_has_extension_data_property_then_property_is_in_serialized_json() { //// Arrange var schema = new JsonSchema4(); schema.ExtensionData = new Dictionary<string, object> { { "Test", 123 } }; //// Act var json = schema.ToJson(); //// Assert Assert.IsTrue(json.Contains( @"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""Test"": 123 }")); }
public async Task Artisans_GetQuote_ShouldReturnCorrectSchema() { var testData = _nautilusHelpers.GetDefaultTestData(ArtisansApplicationStatus.Quoted); var applicationResult = await _testHelpers.CreateApplication(testData); var applicationId = applicationResult.ApplicationId; await _testHelpers.CreateQuote(applicationId); var quoteResult = await _testHelpers.GetQuote(applicationId); quoteResult.StatusCode.Should().Be(HttpStatusCode.OK); JObject quoteObj = JObject.Parse(quoteResult.Quote); var schemaData = _quoteSchema.ToJson(); var schemaErrors = _quoteSchema.Validate(quoteObj); schemaErrors.Count.Should().Be(0); }
public async Task When_discriminator_object_is_set_then_schema_is_correctly_serialized() { //// Arrange var childSchema = new JsonSchema4 { Type = JsonObjectType.Object, }; var schema = new JsonSchema4(); schema.Definitions["Foo"] = childSchema; schema.DiscriminatorObject = new OpenApiDiscriminator { PropertyName = "discr", Mapping = { { "Bar", new JsonSchema4 { Reference = childSchema } } } }; //// Act var json = schema.ToJson(); var schema2 = await JsonSchema4.FromJsonAsync(json); var json2 = schema2.ToJson(); //// Assert Assert.Contains(@"""propertyName"": ""discr""", json); Assert.Contains(@"""Bar"": ""#/definitions/Foo""", json); Assert.Equal(json, json2); Assert.Equal(schema2.Definitions["Foo"], schema2.ActualDiscriminatorObject.Mapping["Bar"].ActualSchema); }
private static void BuildSchema(string name, bool overwrite) { Directory.CreateDirectory(outputSampleDirectory); Directory.CreateDirectory(outputSchemaDirectory); string samplePath = Path.Combine(outputSampleDirectory, name + ".json"); string schemaPath = Path.Combine(outputSchemaDirectory, name + ".schema.json"); if (!File.Exists(schemaPath) || overwrite) { try { JsonSchema4 schema = JsonSchema4.FromSampleJson(File.ReadAllText(samplePath)); File.WriteAllText(schemaPath, schema.ToJson()); } catch (Exception exception) { Console.WriteLine(exception); throw; } } }
public async Task Artisans_Get_ShouldReturnCorrectSchema() { var testData = _nautilusHelpers.GetDefaultTestData(ArtisansApplicationStatus.Open); var createResult = await _httpHelpers.CreateApplication(testData); var applicationId = createResult.ApplicationId; var applicationResult = await _httpHelpers.GetApplication(applicationId); applicationResult.StatusCode.Should().Be(HttpStatusCode.OK); JObject appObj = JObject.Parse(applicationResult.Application); var schemaData = _schema.ToJson(); var schemaErrors = _schema.Validate(appObj); schemaErrors.Count.Should().Be(0); var responseId = int.Parse(appObj.GetValue("id").ToString()); responseId.Should().Be(applicationId); }
public static void GenerateTypeScriptArtifactsFromCSharpType(Type csharpType, string typeScriptFileName, Dictionary <string, string> handWrittenBaseClasses, List <string> interfaces, string templateDirectory, Stream typeScriptFile, Stream jsonDomainModel, string jsonSchemaFile) { if (!Directory.Exists(templateDirectory)) { throw new ArgumentException($"{Assembly.GetExecutingAssembly().Location} || {templateDirectory}"); } var settings = new JsonSchemaGeneratorSettings(); var sourceSchema = new JsonSchema4(); var resolver = new JsonSchemaResolver(sourceSchema, settings); var generator = new JsonSchemaGenerator(settings); generator.GenerateAsync(csharpType, null, sourceSchema, resolver).GetAwaiter().GetResult(); generator.GenerateAsync(typeof(SFProjectUserResource), resolver).GetAwaiter().GetResult(); #region Generate Typescript model objects var typescriptSettings = new TypeScriptGeneratorSettings { // The ExcludedTypeNames should match the C# at this point to match what was generated in the Json Schema ExcludedTypeNames = new List <string>(handWrittenBaseClasses.Keys).ToArray(), ExtensionCode = GenerateBaseClassImports(handWrittenBaseClasses), TemplateDirectory = templateDirectory, ConvertConstructorInterfaceData = false, // skip generating interfaces for the defined types GenerateConstructorInterface = false, MarkOptionalProperties = true }; AdjustTypeInfoInSchema(interfaces, sourceSchema); if (!string.IsNullOrEmpty(jsonSchemaFile)) { File.WriteAllText(jsonSchemaFile, sourceSchema.ToJson()); } var tsGenerator = new TypeScriptGenerator(sourceSchema, typescriptSettings); var tsContents = tsGenerator.GenerateFile(); // Two pass clean-up to the generated code to make interfaces work foreach (var i in interfaces) { //Regex remove any places where we generated a ref that 'extends' an interface var refclassPattern = $"(class .*Ref)( extends {i}Ref)"; tsContents = Regex.Replace(tsContents, refclassPattern, "$1"); //Regex replace any classes which extend interfaces to implement them instead of extending var classPattern = $"(class .*)( extends {i})"; tsContents = Regex.Replace(tsContents, classPattern, $"$1 implements {i}"); } // Get all the types defined in the schema var definedTypes = new List <string>(); foreach (var type in sourceSchema.Definitions) { if (!handWrittenBaseClasses.ContainsKey(type.Key) && !interfaces.Contains(type.Key) && !type.Value.IsEnumeration) { definedTypes.Add(type.Key); } } // Add the starting type from the schema definedTypes.Add(sourceSchema.Title); // Drop Resource out of all base class names var allClasses = new List <string>(HandWrittenBaseClasses.Keys); allClasses.AddRange(definedTypes); tsContents = RenameAbstractClasses(RenameTypePropValues(tsContents), (from s in allClasses orderby s.Length descending select s).ToList()); var streamWriter = new StreamWriter(typeScriptFile); streamWriter.Write(tsContents); streamWriter.Flush(); #endregion var nonRefTypes = new List <string>(handWrittenBaseClasses.Keys); nonRefTypes.AddRange(interfaces); // Get all the types defined in the schema GenerateJsonModelIncludeFile(csharpType.FullName, typeScriptFileName, definedTypes, jsonDomainModel); }
public static JsonSchema4 Clone(JsonSchema4 original) { return(ParseSchema(original.ToJson(), original.DocumentPath)); }
public string ToJson() { return(_schema.ToJson()); }