C#从json样例中提取 模板 及 数据

  背景:将多份不同格式的样例Json数据的格式提取出来,并将数据替换成新的数据。

  思路:一般可以用读写Json的技术遍历到所有非集合的value进行替换,这里我希望将模板提取出来,将来直接填入新的数据。

  模板的格式是个问题,如果用奇怪的字符串来占位,需要进行replace换成新的数据。

  这里笔者注意到String.Format有这样一个重载 public static String Format(String format, params object?[] args);

  给 args 一个 string[] 或者 list<string>.toarray() 即可,因此决定用 {0} {1} 。。。来进行占位,后续用Format拼接成新的数据。

  注意:默认文件路径是写死的,需要自行设置。Json数据判断是非集合的数据的逻辑不全,可能需要修改。

using System;
using System.Collections.Generic;
using System.IO;

namespace Tool
{
    class Program
    {
        static List<string> templateStrList = new List<string>();
        static List<string> dataStrList = new List<string>();
        static string sourceTextPath = @"E:\source.txt";// source
        static string templateTextPath = @"E:\TempTemplate.txt";// template
        static string dataTextPath = @"E:\TempData.txt";// data
        
        static void Main(string[] args)
        {
            string text;
            // 有参数
            if (args.Length > 0)
            {
                //Console.WriteLine($"{args.Length}{Environment.NewLine}{args[0]}");
                text = System.IO.File.ReadAllText(args[0]);
            }
            else
            {
                text = System.IO.File.ReadAllText(sourceTextPath);
            }
            
            string value = "";
            foreach (var line in text.Split($"{Environment.NewLine}"))
            {
                //Console.WriteLine($"#{item}#");// 打印模板所有内容
                //逻辑并不完善 例如 key 中间出现 : 符号
                //用解析 json 的东西来操作更好 性能未对比过
                if (line.IndexOf(":") >= 0)
                {
                    if (line.LastIndexOf(",") >= 0
                        && line.LastIndexOf(",") > line.IndexOf(":"))
                    {
                        value = line.Substring(line.IndexOf(":")+1, line.LastIndexOf(",") - line.IndexOf(":") - 1);

                        //Console.WriteLine(value);// 观察判断的结果
                        dataStrList.Add(value);
                        templateStrList.Add(line.Replace($"{dataStrList[dataStrList.Count - 1]}", $"{{{dataStrList.Count - 1}}}"));
                    }
                    else if(line.LastIndexOf("{") == -1
                        || line.LastIndexOf("{") < line.IndexOf(":"))
                    {
                        value = line.Substring(line.IndexOf(":") + 1, line.Length - line.IndexOf(":") - 1);

                        //Console.WriteLine(value);// 观察判断的结果
                        dataStrList.Add(value);
                        templateStrList.Add(line.Replace($"{dataStrList[dataStrList.Count - 1]}", $"{{{dataStrList.Count - 1}}}"));
                    }
                    else
                    {
                        templateStrList.Add(line);// 无修改
                    }
                }
                else
                {
                    templateStrList.Add(line);// 无修改
                }
            }

            int choice;
            bool ifExit = false;
            while (true)
            {
                if (ifExit) break;
                Console.Clear();
                Console.WriteLine("Press 1 to see template");
                Console.WriteLine("Press 2 to see value");
                Console.WriteLine("Press 3 to see text path");
                Console.WriteLine("Press 4 to set text path");
                Console.WriteLine("Press 5 to save");
                Console.WriteLine("Press 0 to exit");
                if (int.TryParse(Console.ReadLine(), out choice))
                {
                    Console.Clear();
                    switch (choice)
                    {
                        case 0:
                            ifExit = true;
                            break;
                        case 1:
                            foreach (var item in templateStrList)
                            {
                                Console.WriteLine(item);
                            }
                            break;
                        case 2:
                            foreach (var item in dataStrList)
                            {
                                Console.WriteLine(item);
                            }
                            break;
                        case 3:
                            Console.WriteLine(templateTextPath);
                            Console.WriteLine(dataTextPath);
                            break;
                        case 4:
                            templateTextPath = Console.ReadLine();
                            dataTextPath = Console.ReadLine();
                            break;
                        case 5:
                            Write(templateTextPath, templateStrList);
                            Write(dataTextPath, dataStrList);
                            break;
                        default:
                            break;
                    }
                    if (ifExit == false)
                        Console.ReadKey();
                }
            }
        }
        
        private static void Write(string textPath,List<string> formatStrList)
        {
            try
            {
                // 清除旧数据
                FileStream stream = File.Open(textPath, FileMode.OpenOrCreate, FileAccess.Write);
                stream.Seek(0, SeekOrigin.Begin);
                stream.SetLength(0);
                stream.Close();
                // 录入新数据
                StreamWriter sw = new StreamWriter(textPath, false);
                for (int i = 0; i < formatStrList.Count - 1; i++)
                {
                    sw.Write(formatStrList[i]);
                    sw.Write(Environment.NewLine);
                }
                sw.Write(formatStrList[formatStrList.Count - 1]);// 最后一行不转行
                sw.Close();
                Console.WriteLine($"{textPath} set ok");
            }
            catch (Exception)
            {
                Console.WriteLine($"{textPath} set default");
            }
        }
        
        /// <summary>
        /// 用刚才提取来的数据进行拼接,可以用你的其他数据,具体写法请根据实际情况
        /// </summary>
        public string Test()
        {
            List<string> listStr = new List<string>();
            
            string line;
            System.IO.StreamReader file = new System.IO.StreamReader(dataTextPath);
            while ((line = file.ReadLine()) != null)
            {
                System.Console.WriteLine(line);
                listStr.Add(line);
            }
            file.Close();

            string text = System.IO.File.ReadAllText(templateTextPath);
            string.Format(text, listStr.ToArray());
            retuen string.Format(text, listStr.ToArray());
        }
    }
}
View Code

 

posted @ 2022-03-29 10:33  Drake19  阅读(485)  评论(0编辑  收藏  举报