用于将 json 模式转换为示例 JSON 的 C# 库 [英] C# library for converting json schema to sample JSON
问题描述
我正在寻找一个 C# 库,它将根据给定的 JSON 模式生成有效的 JSON 对象.我想制作一个非常简单的 JSON 样本,就像
我见过一些 JavaScript 库,例如 JSON Schema Faker,但我需要一个 C#/.Net 库,我可以在其中在后端代码中生成示例 JSON.
好的,它超级简单,没有考虑 JSON 模式的许多因素,但它可能是一个足够好的起点.它还依赖于 Newtonsoft 的 JsonSchema 库.
公共类 JsonSchemaSampleGenerator{公共 JsonSchemaSampleGenerator(){}公共静态 JToken 生成(JsonSchema 模式){JToken 输出;开关(模式.类型){案例 JsonSchemaType.Object:var jObject = new JObject();if (schema.Properties != null){foreach(schema.Properties 中的 var 属性){jObject.Add(TranslateNameToJson(prop.Key), Generate(prop.Value));}}输出 = jObject;休息;案例 JsonSchemaType.Array:var jArray = new JArray();foreach(schema.Items 中的变量项){jArray.Add(生成(项目));}输出 = jArray;休息;案例 JsonSchemaType.String:输出=新的JValue(样本");休息;案例 JsonSchemaType.Float:输出 = 新 JValue(1.0);休息;案例 JsonSchemaType.Integer:输出 = 新 JValue(1);休息;案例 JsonSchemaType.Boolean:输出=新的JValue(假);休息;案例 JsonSchemaType.Null:输出 = JValue.CreateNull();休息;默认:输出=空;休息;}返回输出;}公共静态字符串 TranslateNameToJson(字符串名称){return name.Substring(0, 1).ToLower() + name.Substring(1);}}
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);
}
}
这篇关于用于将 json 模式转换为示例 JSON 的 C# 库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!