3

My goal is to start using Stream in order to read a HTTP contents (HttpResponseMessage.Content). As for the moment I'm using ReadAsStringAsync to read the content, and I would like to improve the performance and memory usage with ReadAsStreamAsync.

In order to achieve that I've built a small unit test, which should arrange a Stream and then read it and convert it into the original object.

The expected result should be the original object after deserialize, but it returns null.

// Arrenge
List<TypiCode> typiCodes = new List<TypiCode>()
{
    new TypiCode()
    {
        Completed = true,
        Id = this._random.Next(1000),
        Title = Guid.NewGuid().ToString(),
        UserId = this._random.Next(1000)
    }
};

var jsonSerializer = new JsonSerializer();

Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonSerializer.Serialize(jsonWriter, typiCodes);
jsonWriter.Flush();

// Act
List<TypiCode> result = null;
using (var streamReader = new StreamReader(stream))
{
    using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
    {                      
        result = jsonSerializer.Deserialize<List<TypiCode>>(jsonTextReader);
    }
}

//Assert
Assert.IsNotNull(result); --> Failed!

The model:

[Serializable]
public class TypiCode
{
    public int UserId { get; set; }
    public int Id { get; set; }
    public string Title { get; set; }
    public bool Completed { get; set; }
}

Why the StreamReader returning null?

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91

1 Answers1

4

After writing to the stream you are behind the data. You need to get to its start again.

Reset the streams position:

// your code

Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonSerializer.Serialize(jsonWriter, typiCodes);
jsonWriter.Flush();

stream.Seek(0, SeekOrigin.Begin);

// more of youre code

Doku:

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Thanks, any idea why I'm getting now `Unexpected character encountered while parsing value: . Path '', line 1, position 1.`? – Shahar Shokrani Apr 11 '20 at 22:28
  • @shar You use a BinaryFormatter ... and a JsonTextReader to read back in. Does that fit together well? Id suggest exploring in that direction ;) – Patrick Artner Apr 11 '20 at 22:29
  • Hey @Patrick you were right! I've changed into the JsonTextWriter without disposing and it worked! (see updated question) – Shahar Shokrani Apr 11 '20 at 22:59