How to deserialize stream to object using System.Text.Json APIs How to deserialize stream to object using System.Text.Json APIs json json

How to deserialize stream to object using System.Text.Json APIs


I believe that documentation needs to be updated because .NET Core 3 has a method to read from a stream directly. Using it is straight-forward, assuming the stream is encoded in UTF8:

private static readonly JsonSerializerOptions Options = new JsonSerializerOptions();private static async Task<T> Deserialize<T>(HttpResponseMessage response){    var contentStream = await response.Content.ReadAsStreamAsync();    var result = await JsonSerializer.DeserializeAsync<T>(contentStream, Options);    return result;}

One thing to watch out for is that by default HttpClient will buffer the response content in-memory before returning unless you set the HttpCompletionOption to ResponseHeadersRead when invoking SendAsync:

var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);