May 26, 2011

Serializing object to JSON returns empty string?

Consider the following code:

string JSONObject = string.Empty;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(this.GetType());
using (MemoryStream ms = new MemoryStream())
{
    serializer.WriteObject(ms, this);
    // Donchev - we need to reset because the write has gone to the end of the stream
    // and the StreamReader.ReadToEnd() won't seek to the beginning of the stream again.
    using (StreamReader sr = new StreamReader(ms))
    {
        JSONObject = sr.ReadToEnd();
        sr.Close();
        sr.Dispose();
    }
    ms.Close();
    ms.Dispose();
}
return JSONObject;

It seems perfectly correct but have a few problems.

And the first one is very important – it is based on wrong assumption and it is returning empty string because of that.

I will let you tackle it for a while to see if you can find where the problem is.

Ready?

If not – I’ll tell you – the problem is that when I wrote this code, I was expecting the ReadToEnd() method of the StreamReader class to auto reset the stream to its beginning, it sounds for some reason to me that this method it is saying - “Read the whole thing.”.

Unfortunately this assumption evaluated to false.

The method actually says - “Read from where you are to the end of the thing.”.

So before calling JSONObject = sr.ReadToEnd();

I needed to simply call:

ms.Seek(0, SeekOrigin.Begin);

In order to reset the pointer to the beginning of the stream.

Voilla!

The other question I asked myself is why the pointer is at the end of the stream (after the string is empty and not some portion of the stream, it should be at the end).

The answer – the serializer.WriteObject() method is probably not resetting it to be at the beginning after it completes its job.

Not quite sure who is responsible for resetting the stream – the caller or the callee, we can have a long discussion about this.

Anyway – just wanted to share this with you. I know it is very old thing but I am trying to write for much of the things that made an impression on me.

4 comments:

Unknown said...

Thanks for that post. Very helpful. I was actually struggling with JSON serialization for some time.

Unknown said...

Thanks for that post. Very helpful. I was actually struggling with JSON serialization for some time.

Unknown said...

Thanks for that post. Very helpful. I was struggling with JSON serialization for a moment.

Anonymous said...

Thank you so much, I have been struggling with this odd behaviour for an hour!