2016-12-26 108 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 
    } 
}