Search code examples
c#jsonazureazure-blob-storagememorystream

Download blob storage and return Json object


I am trying to download a .json blob that I have stored in a container in the Azure Storage using Newtonsoft.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 doing Json(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 object null

What can I do to accomplish this?

Thank you


Solution

  • 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);
                    }
                }
            }