Serialize into json and return as a stream
Asked Answered
D

2

5

How can I serialize an object into json and return it as a stream?

I have tried:

        using (var stream = new MemoryStream())
        using (var streamWriter = new StreamWriter(stream))
        using (var jsonWriter = new JsonTextWriter(streamWriter))
        {
            var serializer = new JsonSerializer();
            serializer.Serialize(jsonWriter, obj);
            streamWriter.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }

but the stream is always closed.

Next I have tried:

new MemoryStream(Convert.FromBase64String(JsonConvert.SerializeObject(obj)))

But this is not registering as a base64 string and I feel this method is less efficient.

Dour answered 10/10, 2018 at 20:19 Comment(0)
B
16

Ask StreamWriter does not close your stream. And of course avoid stream disposing.

E.g. code will be:

    var stream = new MemoryStream();
    using (var streamWriter = new StreamWriter(stream:stream, encoding:Encoding.UTF8, bufferSize:4096, leaveOpen:true)) // last parameter is important
    using (var jsonWriter = new JsonTextWriter(streamWriter))
    {
        var serializer = new JsonSerializer();
        serializer.Serialize(jsonWriter, obj);
        streamWriter.Flush();
        stream.Seek(0, SeekOrigin.Begin);
        return stream;
    }

Another option - avoid stream closing, because you don't need it (native resources will not be leaked here):

    var stream = new MemoryStream();
    var streamWriter = new StreamWriter(stream)
    var jsonWriter = new JsonTextWriter(streamWriter)

    var serializer = new JsonSerializer();
    serializer.Serialize(jsonWriter, obj);
    jsonWriter.Flush();
    streamWriter.Flush();
    stream.Seek(0, SeekOrigin.Begin);
    return stream;
Backstay answered 10/10, 2018 at 20:28 Comment(0)
T
6

Manushin's answer is correct about not closing the stream before returning it for your first snippet. Regarding your second snippet, base 64 encoding is different than text encoding. To quickly convert a string to a memory stream, you can use Encoding.GetBytes(string) to get a byte array:

var jsonString = JsonConvert.SerializeObject(new { test = "123" });
return new MemoryStream(Encoding.Default.GetBytes(jsonString));
Thalamencephalon answered 10/10, 2018 at 20:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.