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

2

7

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

Outdo answered 15/3, 2019 at 14:2 Comment(0)
D
4

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() + ")");
    }
}
Drogin answered 15/3, 2019 at 14:22 Comment(4)
Would you be kind enough to link to a fork of the fiddle in the question showing how this is done?Outdo
Thank you so much!Outdo
Also realized that you'll need to call Flush() on the writer in order to get it to write to the actual memory stream since it caches some data before it writes it.Drogin
@stuartd Try it in the fiddle, and see you do indeed need to reset the position! Both are required.Outdo
J
1

You need to flush your writer.

new JsonSerializer().Serialize(jsonWriter, new { name = "Jamie" });
jsonWriter.Flush();
Junkie answered 15/3, 2019 at 14:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.