Download blob storage and return Json object

大憨熊 提交于 2019-12-12 08:10:48

问题


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


回答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);
                }
            }
        }



回答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);
}



回答3:


In case you don't care for streaming and want a short and concise way:

var json = await blockBlob.DownloadTextAsync();

var myObject = JsonConvert.DeserializeObject<MyObject>(json);


来源:https://stackoverflow.com/questions/34885801/download-blob-storage-and-return-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!