標籤:dictionary 最佳化 xml c# java
C# 將MSMQ訊息轉換成Json格式 【最佳化】
轉換函式:
private string ConvertToJSON(string label, string body) { //TODO: convert to json string[] Lablelist = label.Split('|'); string[] Bodylist = body.Split('|'); string JsonStr = "{\""; NameValueCollection nvc = (NameValueCollection)ConfigurationManager.GetSection("LableName"); foreach (string key in nvc.AllKeys) { JsonStr = JsonStr + nvc[key] + "\":\"" + Lablelist[Convert.ToInt32(key)-1] + "\",\""; } NameValueCollection nvd = (NameValueCollection)ConfigurationManager.GetSection("BodyName"); foreach (string key in nvd.AllKeys) { JsonStr = JsonStr + nvd[key] + "\":\"" + Bodylist[Convert.ToInt32(key) - 1] + "\",\""; } JsonStr = JsonStr.Remove(JsonStr.Length - 2, 2)+"}"; Console.WriteLine(JsonStr); return JsonStr; }
設定檔:
<?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <section name="LableName" type="System.Configuration.NameValueSectionHandler"/> <!--以NameValue索引值/對的形式返回配置節中的資訊--> <section name="BodyName" type="System.Configuration.NameValueSectionHandler"/> <!--以Dictionary字典索引值對的形式返回配置節中的資訊--> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <LableName> <add key="1" value="MessageID"/> <add key="2" value="SendingBaseTag"/> <add key="3" value="SendingMachineName"/> <add key="4" value="MessageQueuePathName"/> <add key="5" value="CustomField1"/> <add key="6" value="CustomField2"/> </LableName> <BodyName> <add key="1" value="DataMode"/> <add key="2" value="DataModeID"/> <add key="3" value="ExperimentID"/> <add key="4" value="BasePenType"/> <add key="5" value="BasePenTypeID"/> <add key="6" value="MID"/> <add key="7" value="StationTag"/> <add key="8" value="DateTime"/> <add key="9" value="Path1"/> <add key="10" value="EquipmentID1"/> <add key="11" value="Path2"/> <add key="12" value="EquipmentID2"/> </BodyName></configuration>
Thank you!
C# 將MSMQ訊息轉換成Json格式 【最佳化】