title: Using JSON.NET to serialize object into HttpClient's response stream
body: <h1>Abstract</h1>
  <p>Hi, I'm working on a project where it is needed to send potentially huge json of some object via HttpClient, a 10-20 mb of JSON is a typical size. In order do that efficiently I want to use streams, both with Json.Net to serialize an object plus streams for posting data with HttpClient.</p>
  <h1>Problem</h1>
  <p>Here is the snippet for serialization with Json.net, in order to work with streams, Json.net expects a stream that it will write into:</p>
  <pre><code>public static void Serialize( object value, Stream writeOnlyStream )
  {
      StreamWriter writer = new StreamWriter(writeOnlyStream);  &lt;-- Here Json.net expects the stream to be already created
      JsonTextWriter jsonWriter = new JsonTextWriter(writer);
      JsonSerializer ser = new JsonSerializer();
      ser.Serialize(jsonWriter, value );
      jsonWriter.Flush();
  }
  </code></pre>
  <p>While HttpClient expects a stream that it will read from:</p>
  <pre><code>using (var client = new HttpClient())
  {
      client.BaseAddress = new Uri(&quot;http://localhost:54359/&quot;);
  
      var response = await client.PostAsync(&quot;/api/snapshot&quot;, new StreamContent(readOnlyStream)); &lt;-- The same thing here, HttpClient expects the stream already to exist
  
      ... 
  }
  </code></pre>
  <p>So eventually this means that both classes expecting the Stream to be created by someone else, but there are no streams both for Json.Net, neither for HttpClient. So the problem seems that can be solved by implementing a stream that would intercept a read requests made to read-only stream, and issue writes upon request from write-only stream.</p>
  <h1>Question</h1>
  <p>Maybe someone has stumbled on such situation already, and probably found already implemented solution to this problem. If so, please share it with me,</p>
  <p>Thank you in advance!</p>