The task is to serialize the class in json and pass it to POST on the server. I wrote the code and it works, but I have a feeling that I have done a lot of unnecessary things. Prompt good practice to solve my problem.
//package - a serializable object that must be passed
JsonPackage package = new JsonPackage( userData );
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer( typeof( JsonPackage ) );
WebRequest request = WebRequest.Create( "http://localhost:52733/set" );
request.ContentType = "application/json";
request.Method = "POST";
MemoryStream ms = new MemoryStream();
jsonFormatter.WriteObject( ms, package );
ms.Flush();
ms.Position = 0;
StreamReader sr = new StreamReader( ms );
string jsonString = sr.ReadToEnd();
StreamWriter sw = new StreamWriter( request.GetRequestStream() );
sw.Write( jsonString );
sr.Dispose();
sw.Dispose();
ms.Dispose();
request.GetResponse();
UPDATE Thanks to all for the answers, you helped me to learn a lot. I took another advice and wrote as follows:
//package - a serializable object that must be passed
JsonPackage package = new JsonPackage( Data );
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer( typeof( JsonPackage ) );
WebRequest request = WebRequest.Create( "http://localhost:52733/set" );
request.ContentType = "application/json";
request.Method = "POST";
using ( var stream = request.GetRequestStream() )
{
jsonFormatter.WriteObject( stream, package );
}
request.GetResponse();
Tell me there are flaws in my decision?