title: How to deserialize stream to object using System.Text.Json APIs
body: <p>I'm receiving a response from a web api call as a stream and need to deserialize it to a model.</p>
  <p>This is a generic method, so I can't say which parts of code will use this and what's the response payload.</p>
  <p>Here's the method:</p>
  <pre><code>public async Task&lt;T&gt; InvokeAsync&lt;T&gt;(string method)
  {
      Stream response = await this.httpClientWrapper.InvokeAsync(method);
      var serializer = new JsonSerializer();
      using var streamReader = new StreamReader(response);
      using var reader = new JsonTextReader(streamReader);
      return serializer.Deserialize&lt;T&gt;(reader);
  }
  </code></pre>
  <p>I'm trying to remove Newtonsoft and use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.text.json?view=netcore-3.0" rel="noreferrer">System.Text.Json</a> API.</p>
  <p>I found this <a href="https://github.com/dotnet/corefx/blob/61024c30b966ee63c357a491370a2daf94c4c42f/src/System.Text.Json/porting_guide/README.md" rel="noreferrer">porting guide</a> in corefx repo in Github, where section <a href="https://github.com/dotnet/corefx/blob/61024c30b966ee63c357a491370a2daf94c4c42f/src/System.Text.Json/porting_guide/README.md#reading-from-a-string--stream" rel="noreferrer">Reading from a Stream/String</a> states:</p>
  <blockquote>
  <p>We currently (as of .NET Core 3.0 preview 2) do not have a convenient
  API to read JSON from a stream directly (either synchronously or
  asynchronously). For synchronous reading (especially of small
  payloads), you could read the JSON payload till the end of the stream
  into a byte array and pass that into the reader</p>
  </blockquote>
  <p>So following this advise I come up with the following:</p>
  <pre><code>public async Task&lt;T&gt; InvokeAsync&lt;T&gt;(string method)
  {
      Stream response = await this.httpClientWrapper.InvokeAsync(method);
      var length = response.Length;
      var buffer = ArrayPool&lt;byte&gt;.Shared.Rent((int)length);
      var memory = new Memory&lt;byte&gt;(buffer);
      await response.WriteAsync(memory);
      var result = JsonSerializer.Deserialize&lt;T&gt;(memory.Span);
      ArrayPool&lt;byte&gt;.Shared.Return(buffer);
      return result;
  }
  </code></pre>
  <p>So my question is - did I understand the advise correctly and this is the way to go ?</p>
  <p>This implementation probably can be improved on many aspects, but what bothers me most is renting the byte array from the pool e.g. <code>Stream.Length</code> is a long and I convert it to int which can cause <code>OverflowException</code>.</p>
  <p>I tried to look into <a href="https://devblogs.microsoft.com/dotnet/system-io-pipelines-high-performance-io-in-net/" rel="noreferrer">System.IO.Pipelines</a> and use <code>ReadOnlySequence&lt;byte&gt;</code> overloads of JSON API, but it gets very complicated.</p>