如何将网络响应映射到C#类?

时间:2016-12-23 09:16:13

标签: c# serialization deserialization tcpclient networkstream

我尝试通过TCP / IP协议与服务器通信。这是我的方法:

private bool SendTcpRequest<T>(T request, Settings settings)
    {
        try
        {
            TcpClient client = new TcpClient(settings.Url, settings.Port);

            byte[] data = null;

            if (!string.IsNullOrEmpty(request.ToString()))
                data = Encoding.ASCII.GetBytes(request.ToString());
            NetworkStream stream = client.GetStream();

            if (stream.CanWrite)
                stream.Write(data, 0, data.Length);
            else
            {
                return false;
            }

            if (stream.CanRead)
            {
                byte[] myReadBuffer = new byte[client.ReceiveBufferSize];
                IFormatter formatter = new BinaryFormatter();

                do
                {
                    var numberOfBytesRead = stream.Read(myReadBuffer, 0, client.ReceiveBufferSize);

                    responseMessage = new StringBuilder();
                    responseMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
                }
                while (stream.DataAvailable);
            }
            else
            {
                return false;
            }
            stream.Close();
            client.Close();
            return true;
        }
        catch (ArgumentNullException e)
        {
            return false;
        }
        catch (SocketException e)
        {
            return false;
        }
    }

服务器将发送响应如下:

<TOPUPRESPONSE>
     <RESULT>00</RESULT> // status of the transaction
     <RESULTTEXT>transaction successful</RESULTTEXT> //description of the result code
     <TERMINALID>69500002</TERMINALID>
     <TXID>0803170919092</TXID>
     <PRODUCTID>XYZ</PRODUCTID>
</TOPUPRESPONSE>

现在我有一个响应的c#类,我想知道如何将网络响应映射到我的班级。我在这方面很陌生,我甚至不确定我的responseMessage会是什么样子?有人可以提出一些想法吗?

1 个答案:

答案 0 :(得分:2)

如果您正在使用的是

,请根据该广告创建一个类
[XmlRoot(ElementName="TOPUPRESPONSE")]
    public class TOPUPRESPONSE {
        [XmlElement(ElementName="RESULT")]
        public string RESULT { get; set; }
        [XmlElement(ElementName="RESULTTEXT")]
        public string RESULTTEXT { get; set; }
        [XmlElement(ElementName="TERMINALID")]
        public string TERMINALID { get; set; }
        [XmlElement(ElementName="TXID")]
        public string TXID { get; set; }
        [XmlElement(ElementName="PRODUCTID")]
        public string PRODUCTID { get; set; }
    }

然后只需反序列化它就可以将数据作为一个类来使用:

XmlSerializer serializer = new XmlSerializer(typeof(TOPUPRESPONSE ));
MemoryStream memStream = new    MemoryStream(Encoding.UTF8.GetBytes(inputString));
msg resultingMessage = (TOPUPRESPONSE)serializer.Deserialize(memStream);

或使用StringReader:

XmlSerializer serializer = new XmlSerializer(typeof(TOPUPRESPONSE));
StringReader rdr = new StringReader(inputString);
msg resultingMessage = (TOPUPRESPONSE)serializer.Deserialize(rdr);