title: Serialize Newtonsoft JSON to byte array
body: <p>What I am aiming to do is send JSON containing a header object and a compressed data in a field that is byte array.</p>
  <pre><code>[JsonObject(MemberSerialization.OptOut)]
  public class Message
  {
      public Message()
      {
          Header = new Header();
      }
  
      public Header Header { get; set; }
  
  
      public byte[] Data { get; set; }
  }
  </code></pre>
  <p>Byte array is gzip compressed JSON object, but this is not that relevant. Issue I am having is that if I serialize the JSON it gets converted into string and then back to bytes. Issue is, the message size increases quite a bit , since serializing the byte array converts it to string representation.</p>
  <p>I am constrained by maximum message size and I have spiting of compressed data  in place, but when I get to send the JSON containing compressed data in Byte array and Uncompressed header, serializing JSON object puts me way over the message size limit.</p>
  <p>Is there any reliable way of converting JSON object to byte array straight away.</p>
  <pre><code>var stringMessage = JsonConvert.SerializeObject(message,Formatting.None);
  var bytes = Encoding.UTF8.GetBytes(stringMessage);
  
  var stringMessage2 = JsonConvert.SerializeObject(message.TransportHeader, Formatting.None);
  var bytes2 = Encoding.UTF8.GetBytes(stringMessage2);
  
  Message eventMessage = new Message(bytes);
  var bytes3= Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message.Transportdata));
  </code></pre>
  <p>Compressed data size =243905</p>
  <p>Full JSON in Bytes after serialization = 325313</p>
  <p>Just header in bytes size =90</p>
  <p>Just Compressed data serialized and converted back to bytes = 325210, (size increases when data gets serialized by JsonConvert.SerializeObject and string representation is produced)</p>
  <p>It clearly goes up quite a bit and its caused by byte array.</p>