json.net - 用于将 json 模式转换为示例 JSON 的 C# 库

标签 json.net swagger jsonschema

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

enter image description here

我见过一些 JavaScript 库,例如 JSON Schema Faker ,但我需要一个 C#/.Net 库,我可以在我的后端代码中生成示例 JSON。

最佳答案

好吧,它非常简单,没有考虑 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);
        }
    }

关于json.net - 用于将 json 模式转换为示例 JSON 的 C# 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45922832/

相关文章:

javascript - 比较 JSON 返回的参数值

python - 无法在 jsonschema 中使用日期验证

java - 从 json 反序列化到包含枚举的对象的问题

java - 使用 Jersey 配置 Swagger-ui

java - 如何修改 swagger-maven-plugin 中使用的默认 Jackson 映射器

c# - 从 JSON 架构创建 WPF UI

json - 由于 json 指针,Sphinx 无法包含我的 JSON 定义文件

c# - JsonSerializerSettings 线程安全吗?

asp.net-mvc - MVC Web API 出现错误: 'ObjectContent` 1' 类型无法序列化响应正文,构造函数的参数数量不正确

c# - Json GET请求从数组<>对象变化