博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

JSON AST 生成MD

Posted on 2018-12-06 08:58  生命如风  阅读(777)  评论(0编辑  收藏  举报

 

使用 JsonLite 获取 JSON  AST

 

class Program
    {
        static void Main(string[] args)
        {

            string fileName = $"{AppDomain.CurrentDomain.BaseDirectory}\\json.txt";

            //SyntaxTree

            using (var stream = File.OpenRead(fileName))
            {

                JsonObject temp =  Json.CreateAst(stream) as JsonObject;

               string md =  Process(temp);
            }
            
            Console.WriteLine("Hello World!");
        }

        static string Process(JsonObject jsonObject)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("#### 返回参数");
            builder.AppendLine("| 字段  | 类型  | 字段名  | 说明 |");
            builder.AppendLine("| ------------ | ------------ | ------------ | ------------ | ------------ | ");

            //builder.AppendLine(ProcessFix(jsonObject));

            ProcessContent(jsonObject, 0, builder);


            return builder.ToString();
        }

        static string ProcessContent(JsonObject jsonObject, int deep, StringBuilder builder)
        {
            string format = string.Empty;


            if (deep == 0)
                format = "|{0}|{1}|     ||";
            else
            {
                int paddinLeft = 20 + (deep-1) * 20;
                format = "|<span style=\"padding-left: "+paddinLeft.ToString()+"px\">├─ {0}|{1}|     |    |     |";
            }
            

            foreach (var item in jsonObject.Members)
            {
                if (item.Value.GetType() == typeof(JsonNumber))
                    builder.AppendFormat(format, item.Name, "number");

                else if (item.Value.GetType() == typeof(JsonObject))
                {
                    builder.AppendFormat(format, item.Name, "Object");
                    builder.Append(System.Environment.NewLine);
                    ProcessContent(item.Value as JsonObject, deep + 1, builder);
                }
                else if (item.Value.GetType() == typeof(JsonNull))
                    builder.AppendFormat(format, item.Name, "");

                else if (item.Value.GetType() == typeof(JsonBoolean))
                    builder.AppendFormat(format, item.Name, "bool");

                else if (item.Value.GetType() == typeof(JsonString))
                    builder.AppendFormat(format, item.Name, "string");

                else
                    builder.AppendFormat(format, item.Name, "");

                builder.Append(System.Environment.NewLine);
            }


            return string.Empty;
        }

        
    }