Created
June 16, 2023 22:26
-
-
Save tkoenig89/e35d6ffc2979746476893fe00234ab30 to your computer and use it in GitHub Desktop.
A basic JsonSchemaGenerator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class JsonSchemaGenerator | |
| { | |
| public JsonSchema GenerateSchema(Type type) | |
| { | |
| if (type == typeof(string)) | |
| { | |
| return new JsonSchema { Type = "string" }; | |
| } | |
| else if (type == typeof(int) || type == typeof(decimal) || type == typeof(double)) | |
| { | |
| return new JsonSchema { Type = "number" }; | |
| } | |
| else if (type == typeof(bool)) | |
| { | |
| return new JsonSchema { Type = "boolean" }; | |
| } | |
| else if (type == typeof(DateTime)) | |
| { | |
| return new JsonSchema { Type = "string", Format = "date-time" }; | |
| } | |
| else if (type.IsArray) | |
| { | |
| var elementType = type.GetElementType(); | |
| var arraySchema = GenerateSchema(elementType); | |
| return new JsonSchema { Type = "array", Items = arraySchema }; | |
| } | |
| else if (type.IsClass) | |
| { | |
| var properties = type.GetProperties(); | |
| var objectSchema = new JsonSchema { Type = "object", Properties = new Dictionary<string, JsonSchema>() }; | |
| foreach (var property in properties) | |
| { | |
| var propertySchema = GenerateSchema(property.PropertyType); | |
| objectSchema.Properties.Add(property.Name, propertySchema); | |
| } | |
| return objectSchema; | |
| } | |
| throw new NotSupportedException($"Type '{type.Name}' is not supported."); | |
| } | |
| } | |
| public class JsonSchema | |
| { | |
| public string Type { get; set; } | |
| public string Format { get; set; } | |
| public JsonSchema Items { get; set; } | |
| public Dictionary<string, JsonSchema> Properties { get; set; } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment