Using JsonSerializer with MemoryMappedViewStream " '0x00' is invalid after a single JSON value."

243 Views Asked by At

I am passing data between processes using Memory Mapped Files. Both processes are .NET 6.0 applications which share a .dll containing the data class. I had been serializing the data using BinaryFormatter for years but am now working to replace it as it is deprecated. I am trying to serialize the data using System.Text.Json.JsonSerializer instead. Example class:

[Serializable]
public class SimpleDataSource
{
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public int Number { get; set; }
}

Using MemoryMappedViewStream with JsonSerializer isn't working though. As a test I am just serializing an object and then deserializing it back to another instance:

string dataFilePath = Guid.NewGuid().ToString();
using (MemoryMappedFile dataFile = MemoryMappedFile.CreateNew(dataFilePath, 104857600, MemoryMappedFileAccess.ReadWrite))
using (MemoryMappedViewStream dataStream = dataFile.CreateViewStream())
{
    SimpleDataSource original = new SimpleDataSource
    {
        Name = "Example Name",
        Date = new DateTime(1999, 12, 31),
        Number = 191
    };

    JsonSerializer.Serialize(dataStream, original);
    dataStream.Seek(0, SeekOrigin.Begin);

    SimpleDataSource deserialized = JsonSerializer.Deserialize<SimpleDataSource>(dataStream);
}

This throws the following Exception upon deserialization:

System.Text.Json.JsonException: '0x00' is invalid after a single JSON value. Expected end of data. Path: $ | LineNumber: 0 | BytePositionInLine: 65.

This error is unique to MemoryMappedViewStream. If I replace dataStream in the example with a simple MemoryStream it deserializes without issue.

0

There are 0 best solutions below