Dmitry Kazakov
Dmitry Kazakov

Reputation: 1669

How to serialize-deserialize object using HTTP GetAsync method?

After I upgraded the framework of web app from 4.0 to 4.6 I found that there is no more ReadAsAsync() method in HTTP protocol library, instead of ReadAsAsync() there is GetAsync(). I need to serialize my custom object using GetAsync().

The code using ReadAsAsync():

CustomResponse customResponse = client.ReadAsAsync("api/xxx", new StringContent(new JavaScriptSerializer().Serialize(request), Encoding.UTF8, "application/json")).Result; 

Another example based on ReadAsAsync()

CustomResponse customResponse = await Response.Content.ReadAsAsync<CustomResponse>(); 

How to achieve same goal using GetAsync() method ?

Upvotes: 3

Views: 3494

Answers (1)

TTomer
TTomer

Reputation: 356

You can use it this way: (you might want to run it on another thread to avoid waiting for response)

using (HttpClient client = new HttpClient())
{
    using (HttpResponseMessage response = await client.GetAsync(page))
    {
        using (HttpContent content = response.Content)
        {
            string contentString = await content.ReadAsStringAsync();
var myParsedObject = (MyObject)(new JavaScriptSerializer()).Deserialize(contentString ,typeof(MyObject));
        }

    }
}

Upvotes: 4

Related Questions