在寫網路程式時,常常會有從一個模板裡取代特定值並且輸出 html 或 json 的需求。如果是輸出 json,通常會從物件直接 json,但 html 比較沒辦法做到。以這兩種格式而言,其實要做的事情是一樣的。
假設有一個 json template:
{"responseData": { "result":{ "id1": 1, "id2": "2", "id3": 3, "test" : "{key:test}", "testArray": [{key:testArray}] }, "retrunCode": "0", "method": "{key:method}", "service": "money" } }
程式要做的事很簡單,就是將裡面的 {key:test}、{key:testArray}、{key:method} 給替換掉,方法如下:
public string CreateJsonResponse(HybridDictionary table, string DataFormatFilePath) { StringBuilder strResult = null; StreamReader reader = new StreamReader(DataFormatFilePath); strResult = new StringBuilder(reader.ReadToEnd()); foreach (string key in table.Keys) { if (table[key].GetType().IsArray) { List<string> strList = new List<string>(); string[] strOutputArray = (string[])table[key]; foreach (string element in strOutputArray) { strList.Add("\"" + element + "\""); } strResult.Replace("{key:" + key + "}", string.Join(",", strList.ToArray())); } else { strResult.Replace("{key:" + key + "}", table[key].ToString()); } } return strResult.ToString(); }
測試程式碼:
CreateData creater = new CreateData(); HybridDictionary hdData = new HybridDictionary(); hdData.Add("test", "test value"); hdData.Add("method", "test method"); string[] array = new string[] { "1", "2", "3" }; hdData.Add("testArray", array); Console.WriteLine(creater.CreateJsonResponse(hdData, "response.json"));
執行結果:
如果實作 GUI 介面讓一般人員操作,就得從模板中取出所有的 key 並且列出來,方法如下:
public string[] GetKeyListFromTemplate(string DataFormatFilePath) { List<string> listResult = new List<string>(); string template = null; StreamReader reader = new StreamReader(DataFormatFilePath); template = reader.ReadToEnd(); string pattern = @"\{(key\:)[A-Za-z0-9]*}"; Regex reg = new Regex(pattern, RegexOptions.IgnoreCase); MatchCollection matches = reg.Matches(template); foreach (Match match in matches) { listResult.Add(match.Value.Replace("{key:", "").Replace("}", "")); } return listResult.ToArray(); }
測試程式碼:
CreateData creater = new CreateData(); HybridDictionary hdData = new HybridDictionary(); foreach (string key in creater.GetKeyListFromTemplate("response.json")) { Console.WriteLine(key); }
執行結果:
全站熱搜