2016-12-26 109 views
1

我正在使用HttpClient從鏈接中獲取數據。將響應轉換爲可訪問的對象屬性

這裏是我的迴應:

#S7Z OK 
#Mon Dec 26 02:26:58 EST 2016 
image.anchor=168,186 
image.embeddedIccProfile=0 
image.embeddedPhotoshopPaths=0 
image.embeddedXmpData=0 
image.expiration=-1.0 
image.height=373 
image.iccProfile=sRGB IEC61966-2.1 
image.mask=1 
image.photoshopPathnames= 
image.pixTyp=RGB 
image.printRes=72 
image.resolution=34 
image.thumbRes=17 
image.thumbType=2 
image.timeStamp=1481737849826 
image.width=336 

我想這個響應訪問的對象轉換。

這裏是我的httpclient工作:

using (var client = getHttpClient()) 
{ 
    HttpResponseMessage response = await client.GetAsync(path); 
    if (response.IsSuccessStatusCode) 
    { 
     //var imageData = await response.Content.ReadAsAsync<imageData>(); 
     //imageData.timeStamp 
    } 
    else 
    { 
     //TODO: Need to handle error scenario 
    } 
} 

我已經添加評論,讓你知道我想要做的。其實,我想從響應中獲得image.timeStamp的值。

謝謝!

回答

4

你可以做到這一點通過存儲在字典中的響應,那麼您可以訪問任何成員作爲var x= dic["timeStamp"];,你也可以通過轉換成dic延長dynamic object實施。

編輯:

Stream receiveStream = response.GetResponseStream(); 
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8); 
var text = readStream.ReadToEnd(); 
// Split the content into chunks 
foreach(var ch in chunks) 
{ 
     string[] kv = ch.Split('=');     
     dic.Add(kv[0], kv[1]); 
} 
+0

感謝您的回答。你能告訴我如何將這個響應數據轉換成Dictionary? – Saadi

+1

這似乎是一個不錯的選擇。謝謝!但它在Dictionary中有一些錯誤的值。我使用正則表達式來修復它。 – Saadi

0

這裏是我做過什麼,使其工作。 (在doe_deo的幫助下回答)

using (var client = getHttpClient()) 
{ 
    HttpResponseMessage response = await client.GetAsync(path); 
    if (response.IsSuccessStatusCode) 
    { 
     var data = await response.Content.ReadAsStringAsync(); 
     Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
     var rx = new Regex(@"(.*?)\s*=\s*([^\s]+)"); 
     foreach (Match m in rx.Matches(data)) 
     { 
      dictionary.Add(m.Groups[1].ToString(), m.Groups[2].ToString()); 
     } 
    } 
    else 
    { 
     //TODO: Need to handle error scenario 
    } 
}