Diego
Diego

Reputation: 2372

c# ReadAsJsonAsync in framework 4.5

I am used to work in Net Core. When I call a RestApi I read retrieved data like this.

  HttpResponseMessage response = client.PostAsJsonAsync(url, param).Result;
    value = response.Content.ReadAsJsonAsync<R>().Result;

Now, I am back in Framework 4.5 and i need a replace to

ReadAsJsonAsync

What is the best way to replace it?

Thanks

Upvotes: 2

Views: 5424

Answers (1)

mm8
mm8

Reputation: 169330

You could just install the Newtonsoft.Json NuGet package and implement the ReadAsJsonAsync extension method yourself. It's pretty simple:

public static class HttpClientExtensions
{
    public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content)
    {
        var dataAsString = await content.ReadAsStringAsync();
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(dataAsString);
    }
}

By the way, you should await async methods and not block on the Result property:

value = await response.Content.ReadAsJsonAsync<R>();

Upvotes: 4

Related Questions