Reputation: 11677
Internally, JsonConvert.SerializeObject(obj, Formatting.Indented)
boils down to
JsonSerializer jsonSerializer = JsonSerializer.Create(null);
StringWriter stringWriter = new StringWriter(new StringBuilder(256), (IFormatProvider) CultureInfo.InvariantCulture);
using (JsonTextWriter jsonTextWriter = new JsonTextWriter((TextWriter) stringWriter))
{
jsonTextWriter.Formatting = formatting;
jsonSerializer.Serialize((JsonWriter) jsonTextWriter, value);
}
return stringWriter.ToString();
This works just fine. However, if I do the following:
string json;
JsonSerializer jsonSerializer = JsonSerializer.Create();
using (var stream = new MemoryStream())
using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
using (var jsonWriter = new JsonTextWriter(streamWriter))
{
serializer.Serialize(jsonWriter, cmd);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
json = reader.ReadToEnd();
}
}
Then the value of json
is ""
. Can anyone point me to my mistake?
Upvotes: 16
Views: 13034
Reputation: 19070
I guess that either JsonTextWriter
or StreamWriter
do some internal buffering. So try to flush the jsonWriter
and/or the streamWriter
before reading from the underlying memory stream.
Upvotes: 2
Reputation: 1503799
The problem is that you haven't flushed the streamWriter
after writing:
serializer.Serialize(jsonWriter, cmd);
streamWriter.Flush();
stream.Position = 0;
Alternatively, why not just use a StringWriter
to start with?
using (var writer = new StringWriter())
{
using (var jsonWriter = new JsonTextWriter(writer))
{
serializer.Serialize(jsonWriter, cmd);
Console.WriteLine(writer.ToString());
}
}
Upvotes: 21