Convert Stream data to custom object in C#.net

I want to convert stream data from response stream into a custom object.

I want to convert respose stream into custom object,I am following these steps.

My code is as follows.

myMethod()               
{
    state s = new state();
    Stream receiveStream;
    StreamReader readStream;
    HttpWebRequest request;
    HttpWebResponse response;
    try
    {
        request = (HttpWebRequest)WebRequest.Create (url);
        request.Method = "GET";  
        request.ContentType = "application/json";
        response = (HttpWebResponse)request.GetResponse ();
        receiveStream = response.GetResponseStream();

        readStream = new StreamReader(receiveStream);
        Console.WriteLine (readStream.ReadToEnd());
        serializer = new DataContractJsonSerializer(typeof(state));
        s = serializer.ReadObject(readStream.BaseStream)as state;
        Console.Write(s.name+"\n"); 

        response.Close ();
        readStream.Close ();    

    }
    catch (Exception ex)
    {
    }
}

Object s returning nothing. Can anyone help me?

Jon Skeet
people
quotationmark

The trouble is that you're trying to deserialize an object when you've already read all the data from it just beforehand:

readStream = new StreamReader(receiveStream);
Console.WriteLine (readStream.ReadToEnd());

After those line, the stream will be empty, so there's nothing to deserialize. Get rid of those lines (then use receiveStream below), and you may well find it just works.

Additionally, a few suggestions:

  • Rather than closing streams explicitly, use using statements
  • Add a using statement for the response itself, as that implements IDisposable
  • Keep the scope of each variable as small as it can be, assigning a value at the point of declaration
  • It's rarely a good idea to catch Exception, and it's almost never a good idea to just swallow exceptions in the way that you are doing, with no logging etc
  • Follow .NET naming conventions, where state would be State (and possibly make the name a bit more descriptive anyway)
  • Use a cast rather than as - see my blog post on the topic for reasons

people

See more on this question at Stackoverflow