2016-10-04 109 views
1

我正在使用azure blob存儲來存儲JSON文件,並在我的代碼中使用C#API下載它。CloudBlockBlob.DownloadTextAsync返回無效文本

當我下載文本文件的內容並嘗試使用JsonConvert對其進行反序列化時,出現錯誤(Visual Studio JSON可視化工具也顯示文本錯誤)。但是,如果我複製文本並粘貼到JSONLint.com中,它看起來很好。另外,如果我手動從Azure存儲下載文件並在代碼中讀取文件,則它反序列化就好了。我使用C#API下載時遇到無效數據的任何想法?

var storageAccount = CloudStorageAccount.Parse(connectionString); 
var blobClient = storageAccount.CreateCloudBlobClient(); 
var container = blobClient.GetContainerReference(containerName); 
var blob = container.GetBlockBlobReference(folderAndFileName); 
var text = await blob.DownloadTextAsync(); 
var obj = JsonConvert.DeserializeObject(text); 
// Exception: "Unexpected character encountered while parsing value: . Path '', line 0, position 0." 

注:我通過PowerShell的上傳文件:

$blobProperties = @{"ContentType" = "application/json"}; 
Set-AzureStorageBlobContent -Container $containerName -File $LocalFilePath -Blob $RemoteBlobName -BlobType "Block" -Properties $blobProperties 
+0

您的代碼對我來說確實很好。您能否告訴您正在使用的存儲客戶端庫的版本?另外,您是否可以分享您上傳的JSON文件?我想嘗試使用該文件。 –

回答

1

我已經測試你的代碼。看來,這個問題不是關於你的代碼。下面是我用你的代碼測試結果:

enter image description here

實體:

public class People 
    { 
     [JsonProperty(PropertyName ="name")] 
     public string Name { get; set; } 
     [JsonProperty(PropertyName = "address")] 
     public string Address { get; set; } 
    } 

JSON文件:

{ 
    "name": "jambor", 
    "address": "us" 
} 

由於Gaurav Mantri說,我會建議你檢查你的storage library。我的Azure存儲庫的版本是7.2.1。請在代碼var obj = JsonConvert.DeserializeObject(text);處設置斷點。然後檢查文本的值。它可以幫助你找出問題。

1

經過進一步調查後,我發現下載的文件在開始時有一個額外的Unicode格式化字符。我添加了下面的代碼來檢查開頭的特殊字符並刪除它們...

var startIndex = 0; 
while (char.GetUnicodeCategory(text, startIndex) == UnicodeCategory.Format) 
{ 
    startIndex++; 
} 
text = text.Substring(startIndex, text.Length - startIndex);