Search code examples
c#streamsystem.text.jsonjsonserializer

How to create a JSON stream of UTF8 bytes in C#


I´m trying to write Unit Tests for an extension method of stream which internally uses

return await JsonSerializer
            .DeserializeAsync(@this, type, options ?? JsonFlatOptions)
            .ConfigureAwait(false);

where @this would be my stream

I tried

var dog = new Dog() { Name = "Merlina" };

byte[] jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(dog);
var json = JsonSerializer.Serialize(dog);

var stream = new MemoryStream();
stream.Write(jsonUtf8Bytes, 0, jsonUtf8Bytes.Length);

But when trying to deserialize it I get the following error message:

System.Text.Json.JsonException : The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
  ----> System.Text.Json.JsonReaderException : The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. LineNumber: 0 | BytePositionInLine: 0.

I´m trying to get an appropriate stream to use

The documentations says that this method Deserializes a JSON stream of UTF8 bytes into a dynamic object.


Solution

  • The problem is that you are not resetting the stream back to the beginning.

    You need to do

    stream.Position = 0;
    

    But honestly, it's much better to just use the array itself as the backing array for the stream, like this

    var stream = new MemoryStream(jsonUtf8Bytes);