Jamie Twells
Jamie Twells

Reputation: 2144

Trying to serialize an object to a stream using Newtonsoft, getting an empty stream

I have an example of a program:

using System;
using Newtonsoft.Json;
using System.IO;

public class Program
{
    public static void Main()
    {
        using (var stream = new MemoryStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        using (var jsonWriter = new JsonTextWriter(writer))
        {
            new JsonSerializer().Serialize(jsonWriter, new { name = "Jamie" });
            Console.WriteLine("stream length: " + stream.Length); // stream length: 0
            Console.WriteLine("stream position: " + stream.Position); // stream position: 0
            Console.WriteLine("stream contents: (" + reader.ReadToEnd() + ")"); // stream contents: ()
        }
    }
}

It should (according to this page: https://www.newtonsoft.com/json/help/html/SerializingJSON.htm) make a stream containing a JSON representation of the object: obj but in reality the stream appears to have length 0 and is an empty string when written out. What can I do to achieve the correct serialization?

Here is an example of the program running: https://dotnetfiddle.net/pi1bqE

Upvotes: 7

Views: 2136

Answers (2)

Eric Damtoft
Eric Damtoft

Reputation: 1425

You'll need to flush the JsonSerializer to make sure it's actually written data to the underlying stream. The stream will be at the end position so you'll need to rewind it back to the start position to read the data.

public static void Main()
{
    using (var stream = new MemoryStream())
    using (var reader = new StreamReader(stream))
    using (var writer = new StreamWriter(stream))
    using (var jsonWriter = new JsonTextWriter(writer))
    {
        new JsonSerializer().Serialize(jsonWriter, new { name = "Jamie" });

        jsonWriter.Flush();
        stream.Position = 0;

        Console.WriteLine("stream contents: (" + reader.ReadToEnd() + ")");
    }
}

Upvotes: 4

Vok
Vok

Reputation: 467

You need to flush your writer.

new JsonSerializer().Serialize(jsonWriter, new { name = "Jamie" });
jsonWriter.Flush();

Upvotes: 1

Related Questions