【问题标题】:Convert response to accessible object properties将响应转换为可访问对象属性
【发布时间】:2016-12-26 07:37:27
【问题描述】:

我正在使用 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
    }
}

我添加了 cmets 让您知道我想要做什么。实际上,我想从响应中获取image.timeStamp 值。

谢谢!

【问题讨论】:

    标签: c# asp.net asp.net-web-api httpclient


    【解决方案1】:

    您可以通过将响应存储在字典中来做到这一点,然后您可以以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]);
    }
    

    【讨论】:

    • 感谢您的回答。你能告诉我如何将这个响应数据转换成字典吗?
    • 这似乎是一个不错的选择。谢谢!但它在字典中有一些错误的值。我已经使用正则表达式来修复它。
    【解决方案2】:

    这是我为使其工作所做的工作。 (在 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2014-04-01
      • 1970-01-01
      • 2017-10-17
      • 2015-12-14
      • 1970-01-01
      • 2014-07-05
      • 2014-11-12
      • 2022-01-10
      相关资源
      最近更新 更多