Question: Convert response to accessible object properties

Question

Convert response to accessible object properties

Answers 2
Added at 2016-12-26 08:12
Tags
Question

I'm using HttpClient to get data from a link.

Here is my response:

#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

I want to convert this response to accessible object.

Here is my httpclient work:

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
    }
}

I've added comments to make you idea what I want to do. Actually, I want to get image.timeStamp value from response.

Thanks!

Answers
nr: #1 dodano: 2016-12-26 09:12

You can do that by storing the response in Dictionary then you can access any member as var x= dic["timeStamp"];, you can also extend the implementation by converting dic into dynamic object.

Edit:

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]);
}
nr: #2 dodano: 2016-12-26 09:12

Here is what I did to make it work. (with help of doe_deo answer)

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
    }
}
Source Show
◀ Wstecz