Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.Net fails to serialize to a stream, but works just fine serializing to a string

Tags:

c#

.net

json.net

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?

like image 1000
moswald Avatar asked Mar 23 '12 19:03

moswald


People also ask

How to deserialize a JSON string in c#?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is JSON serialization and deserialization in c#?

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.

Which of the following attribute should be used to indicate the property must not be serialized while using JSON serializer?

Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.


Video Answer


1 Answers

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());
    }
}
like image 78
Jon Skeet Avatar answered Oct 31 '22 20:10

Jon Skeet