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:
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With