首页 > 代码库 > C# 将MSMQ消息转换成Json格式

C# 将MSMQ消息转换成Json格式

PS:主要就是一个配置文件和一个转换函数


配置文件app.config  之前要ADD reference -->   system.configuration & using.system.configuration

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="Lable.Port1" value="http://www.mamicode.com/MessageID"/>
    <add key="Lable.Port2" value="http://www.mamicode.com/SendingBaseTag"/>
    <add key="Lable.Port3" value="http://www.mamicode.com/SendingMachineName"/>
    <add key="Lable.Port4" value="http://www.mamicode.com/MessageQueuePathName"/>
    <add key="Lable.Port5" value="http://www.mamicode.com/CustomField1"/>
    <add key="Lable.Port6" value="http://www.mamicode.com/CustomField2"/>

    <add key="Body.Port1" value="http://www.mamicode.com/DataMode"/>
    <add key="Body.Port2" value="http://www.mamicode.com/DataModeID"/>
    <add key="Body.Port3" value="http://www.mamicode.com/ExperimentID"/>
    <add key="Body.Port4" value="http://www.mamicode.com/BasePenType"/>
    <add key="Body.Port5" value="http://www.mamicode.com/BasePenTypeID"/>
    <add key="Body.Port6" value="http://www.mamicode.com/MID"/>
    <add key="Body.Port7" value="http://www.mamicode.com/StationTag"/>
    <add key="Body.Port8" value="http://www.mamicode.com/DateTime"/>
    <add key="Body.Port9" value="http://www.mamicode.com/Path1"/>
    <add key="Body.Port10" value="http://www.mamicode.com/EquipmentID1"/>
    <add key="Body.Port11" value="http://www.mamicode.com/Path2"/>
    <add key="Body.Port12" value="http://www.mamicode.com/EquipmentID2"/>
  </appSettings>

</configuration>

转换函数:

    private string ConvertToJSON(string label, string body)
        {
            //TODO: convert to json
            string[] Lablelist = label.Split(‘|‘);
            string[] Bodylist = body.Split(‘|‘);
            
            string[] LableName = new string[6];
            string[] BodyName = new string[12];
            
            string JsonStr = "{\"";
        
            for(int j=1;j<7;j++)
            {
                 
                 JsonStr  = JsonStr + ConfigurationManager.AppSettings["Lable.Port" + j.ToString()] +"\":\""+Lablelist[j-1] + "\",\"";
                 
            }
            for (int i = 1; i < 13;i++ )
            {
                JsonStr = JsonStr + ConfigurationManager.AppSettings["Body.Port" + i.ToString()] + "\":\"" + Bodylist[i - 1] + "\",\"";
            }

            JsonStr = JsonStr.Remove(JsonStr.Length - 2, 2)+"}";

        }
由于不是计算机专业,研究了下 花了5个小时
是不是非常easy?
(*^__^*) 嘻嘻

C# 将MSMQ消息转换成Json格式