This works for all properties:
string resultAsString = await httpResponseMessage.Content.ReadAsStringAsync();
return await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<ApiData>(resultAsString));
while this works only for some of them:
return await httpResponseMessage.Content.ReadAsAsync<ApiData>();
what is the difference?
Provides methods for converting between . NET types and JSON types.
DeserializeObject Method. Deserializes the JSON to a . NET object.
ReadAsAsync Method (HttpContent, Type, CancellationToken) Returns a Task that will yield an object of the specified type from the content instance using one of the provided formatters to deserialize the content.
ReadAsStringAsync(CancellationToken)Serialize the HTTP content to a string as an asynchronous operation.
The former reads asynchronously from the stream, and then uses a thread-pool thread to deserialize the JSON string to an object.
The latter reads asynchronously from the stream, but transforms the JSON string to an object synchronously, on the thread in which resumed after awaiting the asynchronous read from the stream.
Internally, both methods will utilize Json.NET to parse the data, as the extension method HttpContentExtensions.ReadAsAsync<T>
will internally call the JsonMediaTypeFormatter
, which uses Json.NET.
Personally, I'd use the latter, as I see no benefit in executing the serialization on a background thread. But, test your code and see if that works for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With