Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ReadAsAsync and JsonConvert

Tags:

json

c#

json.net

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?

like image 854
Senj Avatar asked Dec 18 '15 11:12

Senj


People also ask

What is Jsonconvert?

Provides methods for converting between . NET types and JSON types.

What does Jsonconvert DeserializeObject do?

DeserializeObject Method. Deserializes the JSON to a . NET object.

How does ReadAsAsync work?

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.

What is ReadAsStringAsync?

ReadAsStringAsync(CancellationToken)Serialize the HTTP content to a string as an asynchronous operation.


1 Answers

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.

like image 126
Yuval Itzchakov Avatar answered Sep 30 '22 18:09

Yuval Itzchakov