C# library for converting json schema to sample JSON

眉间皱痕 提交于 2020-08-03 02:48:55

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/45922832/c-sharp-library-for-converting-json-schema-to-sample-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!