1. 程式人生 > 其它 >C#從json樣例中提取 模板 及 資料

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