I have 2 specific questions with regards to passing a System.IO.Stream
(from a method) and deserialization into object (another method).
XML Response I get from a WebRequest
(please note there are no root tags)
<?xml version="1.0" encoding="UTF-8"?>
<response id="-2d953936:14174bb0cf3:-5213">
<date>2013-10-01 12:01:55.532999</date>
<status>
<current>open</current>
<next>after</next>
<change_at>16:00:00</change_at>
</status>
<message>Market is open</message>
<unixtime>1380643315</unixtime>
</response>
Method 1 - ResponseMethod - Currently returning string
private static string GetResponse(HttpWebRequest request)
{
var v_Response = request.GetResponse();
var v_DataStream = v_Response.GetResponseStream();
var v_Reader = new System.IO.StreamReader(v_DataStream);
var x_XMLResponse = v_Reader.ReadToEnd();
//Close all Stream logic
v_Reader.Close(); v_DataStream.Close(); v_Response.Close();
return x_XMLResponse;
}
Method 2 - Convert the XML to an object
// I would use XDocument and Lin2XML to get my typed object - for example MarketStatus
Questions are:
StreamReader
and then use that as an input into method 2 to get my typed object. Is that a standard approach or there are better ways to this? Additional Note:
MarketStatus
Class Any code snippets/suggestions will really appreciate
We typically use a generic method, similar to the following (simplified for posting), which uses the XMLSerializer to deserialize an XML string representation into the corresponding object.
public T ReturnObjectfromXml<T>(string xmlForm)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
StringReader sr = new StringReader(xmlForm);
XmlTextReader xts = new XmlTextReader(sr);
return ((T)xs.Deserialize(xts));
}
Hope this helps.
Regards,
It looks like you are doing some type of message passing . You will be better off using WCF or ASP.NET Web API instead of rolling your own infrastructure code (to serialize and de-serialize).
To answer question 1: No, it is better to return a string and dispose of the reader as soon as you are done with it. See When should I dispose my objects in .NET?
Comment on note 1: In most cases, you wouldn't want to unit test the serialization/deserialization.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.