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.