Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# library for converting json schema to sample JSON

I'm looking for a C# library that will generate a valid JSON object based on a given JSON Schema. I'd like to produce a very simple JSON sample just like how Swagger does it:

enter image description here

I've seen some JavaScript libraries like JSON Schema Faker, but I need a C#/.Net library where I can generate sample JSON in my backend code.

like image 225
Tom Schreck Avatar asked Aug 28 '17 15:08

Tom Schreck


1 Answers

Ok, it is super simplistic and doesn't take into account many factors of JSON schema, but it might be a good enough starting point for you. It also depends on the JsonSchema library from Newtonsoft.

   public class JsonSchemaSampleGenerator
    {
        public JsonSchemaSampleGenerator()
        {
        }

        public static JToken Generate(JsonSchema schema)
        {
            JToken output;
            switch (schema.Type)
            {
                case JsonSchemaType.Object:
                    var jObject = new JObject();
                    if (schema.Properties != null)
                    {
                        foreach (var prop in schema.Properties)
                        {
                            jObject.Add(TranslateNameToJson(prop.Key), Generate(prop.Value));
                        }
                    }
                    output = jObject;
                    break;
                case JsonSchemaType.Array:
                    var jArray = new JArray();
                    foreach (var item in schema.Items)
                    {
                        jArray.Add(Generate(item));
                    }
                    output = jArray;
                    break;

                case JsonSchemaType.String:
                    output = new JValue("sample");
                    break;
                case JsonSchemaType.Float:
                    output = new JValue(1.0);
                    break;
                case JsonSchemaType.Integer:
                    output = new JValue(1);
                    break;
                case JsonSchemaType.Boolean:
                    output = new JValue(false);
                    break;
                case JsonSchemaType.Null:
                    output = JValue.CreateNull();
                    break;

                default:
                    output = null;
                    break;

            }


            return output;
        }

        public static string TranslateNameToJson(string name)
        {
            return name.Substring(0, 1).ToLower() + name.Substring(1);
        }
    }
like image 194
Darrel Miller Avatar answered Sep 28 '22 01:09

Darrel Miller