.NET API Documentation

HttpResponseMessage.Content.ReadAsJsonAsync Method

Reads the HTTP response content and deserializes it to a JSON object of the specified type.

Signature

public Task<T> ReadAsJsonAsync<T>(JsonSerializerOptions? options = null, CancellationToken cancellationToken = default);

Parameters

Name Type Description
options JsonSerializerOptions? Optional settings to control the JSON deserialization behavior. If null, default settings are used.
cancellationToken CancellationToken A token that can be used to cancel the operation.

Returns

Type Description
Task<T> A task that represents the asynchronous operation. The value of the task contains the deserialized JSON object.

Type Parameters

T: The type to which the JSON content should be deserialized.

Remarks

This method is an extension method and requires the System.Net.Http.Json NuGet package to be installed.

The JSON content is read from the HttpContent associated with the HttpResponseMessage.

The deserialization process uses System.Text.Json by default.

Note: Ensure that the JSON response from the server is compatible with the target type T. Mismatched types or invalid JSON will result in a deserialization error.

Example

using System.Net.Http;
using System.Net.Http.Json; // Required for ReadAsJsonAsync
using System.Threading.Tasks;

public class Example
{
    public class User
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public string? Email { get; set; }
    }

    public async Task FetchUserAsync(HttpClient client, string userId)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync($"api/users/{userId}");
            response.EnsureSuccessStatusCode(); // Throws an exception if the status code is not a success code

            User? user = await response.Content.ReadAsJsonAsync<User>();

            if (user != null)
            {
                Console.WriteLine($"User Name: {user.Name}, Email: {user.Email}");
            }
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"Request error: {e.Message}");
        }
        catch (JsonException e)
        {
            Console.WriteLine($"JSON deserialization error: {e.Message}");
        }
    }
}

See Also