Download blob storage and return Json object
Solution 1
Please reset the stream's position to 0
after reading the blob into the stream. So your code would be:
using (var stream = new MemoryStream())
{
blob.DownloadToStream(stream);
stream.Position = 0;//resetting stream's position to 0
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
{
using (var jsonTextReader = new JsonTextReader(sr))
{
var result = serializer.Deserialize(jsonTextReader);
}
}
}
Solution 2
Both the question and accepted answer start by copying the entire stream into a MemoryStream
which is effectively a big byte array in memory. This step is unnecessary - it's more memory-efficient to stream the blob data directly to the object without buffering the bytes first:
using (var stream = await blob.OpenReadAsync())
using (var sr = new StreamReader(stream))
using (var jr = new JsonTextReader(sr))
{
result = JsonSerializer.CreateDefault().Deserialize<T>(jr);
}
Luis Lavieri
Updated on June 09, 2022Comments
-
Luis Lavieri almost 2 years
I am trying to download a
.json
blob that I have stored in a container in theAzure Storage
usingNewtonsoft.Json
to write it to an object.I am doing this by calling:
(CloudBlockBlob) blob.DownloadToStream(stream);
However, instead of writing the stream to a file in the local app directory, I want to return the json
object
doingJson(result)
This is what I have tried:
using (var stream = new MemoryStream()) { blob.DownloadToStream(stream); var serializer = new JsonSerializer(); using (var sr = new StreamReader(stream)) { using (var jsonTextReader = new JsonTextReader(sr)) { result = serializer.Deserialize(jsonTextReader); } } }
At the end my
jsonTextReader
variable is empty and the objectnull
What can I do to accomplish this?
Thank you