问题
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