I found some code on SO showing how to serialize a C# object to an Azure blog via a stream. This 2018 vintage code used NewtonSoft JSON serialization and I decided to amend the code to work with System.Text.Json.
The resulting code is so much simpler I am concerned I have taken a shortcut too far that will be problematic later.
Is stream based serialization with System.Text.Json as simple to express as it appears?
New Code
public static class BlobExtensions
{
public static async Task AppendObjectAsJsonAsync( this AppendBlobClient blob, object obj )
{
using var stream = await blob.OpenWriteAsync( false );
await JsonSerializer.SerializeAsync( stream, obj );
}
}
Original Newtonsoft Code
public static class BlobExtensions
{
public static async Task SerializeObjectToBlobAsync(this CloudBlockBlob blob, object obj)
{
using (Stream stream = await blob.OpenWriteAsync())
using (StreamWriter sw = new StreamWriter(stream))
using (JsonTextWriter jtw = new JsonTextWriter(sw))
{
JsonSerializer ser = new JsonSerializer();
ser.Serialize(jtw, obj);
}
}
}
The new code works with both AppendBlobClient and BlockBlobClient, I am showing the AppendBlobClient example because that it a better fit for my applications.