将JSON模式转换为示例JSON的C#库

5
我正在寻找一个C#库,它可以根据给定的JSON Schema生成有效的JSON对象。我想要像Swagger一样生成一个非常简单的JSON示例:

enter image description here

我已经看到了一些JavaScript库,比如JSON Schema Faker,但我需要一个C#/.Net库,在我的后端代码中生成示例JSON。

我写了一个简单的程序,我只需要找到一种方法使其成为开源软件。让它能够运行起来并不难。让我看看能否提供一段代码片段来帮助你入门。 - Darrel Miller
在 Stack Overflow 上,询问我们推荐或寻找书籍、工具、软件库、教程或其他外部资源的问题是不符合主题的。 - I4V
1个回答

10

好的,它非常简单,没有考虑JSON模式的许多因素,但这可能是一个足够好的起点。 它还依赖于Newtonsoft的JsonSchema库。

   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);
        }
    }

非常感谢。这正是我需要的,让我开始了。 - Tom Schreck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接