从Json Schema生成Json示例 [英] Generate Json sample from Json Schema
本文介绍了从Json Schema生成Json示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是libarry Json.NET架构的用户,是否有用于生成json的函数通过给定的json模式进行采样?
I'm a user for libarry Json.NET Schema, is there a function for generate json sample by given the json schema?
推荐答案
我终于尝试了另一种获取结果的方法,请参考以下函数:
I finally tried another way to get the result, refer the function:
/// <summary>
/// Generate a random Json sample based on json schema
/// </summary>
/// <param name="schema"></param>
/// <returns>a random Json sample</returns>
public static JToken GenerateJsonSample(this JSchema schema)
{
JToken output;
switch (schema.Type)
{
case JSchemaType.Object:
var jObject = new JObject();
if (schema.Properties != null)
{
foreach (var prop in schema.Properties)
{
jObject.Add(LowerCaseFirstChar(prop.Key), GenerateJsonSample(prop.Value));
}
}
output = jObject;
break;
case JSchemaType.Object | JSchemaType.Null:
var jObject2 = new JObject();
if (schema.Properties != null)
{
foreach (var prop in schema.Properties)
{
jObject2.Add(LowerCaseFirstChar(prop.Key), GenerateJsonSample(prop.Value));
}
}
output = jObject2;
break;
case JSchemaType.Array:
var jArray = new JArray();
foreach (var item in schema.Items)
{
jArray.Add(GenerateJsonSample(item));
}
output = jArray;
break;
case JSchemaType.Array | JSchemaType.Null:
var jArray2 = new JArray();
foreach (var item in schema.Items)
{
jArray2.Add(GenerateJsonSample(item));
}
output = jArray2;
break;
case JSchemaType.String:
output = new JValue("string_sample");
break;
case JSchemaType.String | JSchemaType.Null:
output = new JValue("nullable_string_sample");
break;
case JSchemaType.Number:
output = new JValue(1.0);
break;
case JSchemaType.Integer:
output = new JValue(1);
break;
case JSchemaType.Boolean:
output = new JValue(false);
break;
case JSchemaType.Null:
output = JValue.CreateNull();
break;
default:
output = null;
break;
}
return output;
}
private static string LowerCaseFirstChar(string name)
{
return name.Substring(0, 1).ToLower() + name.Substring(1);
}
然后,您的呼叫代码将是:
then, your calling code would be:
var sampleJsonContent = yourJSchema.GenerateJsonSample().ToString();
这篇关于从Json Schema生成Json示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文