Download blob storage and return Json object

我与影子孤独终老i 提交于 2019-12-03 15:42:06

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

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

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