title: How to determine if a InputStream contains JSON data?
body: <p>How do I check if the data behind a <code>java.io.InputStream</code> (from <code>File</code>, <code>URL</code>, ..) is of type JSON?</p>
  
  <hr>
  
  <p>Of course to be complete the best would be to load the whole data of the stream and try to validate it as JSON (e.g checking for closing bracket <code>}</code>). Since the stream source might be very big (a GeoJSON file with a size of 500MB) this eventually end in a burning machine.</p>
  
  <p>To avoid this I wrote a small method that only takes the first character of the <code>InputStream</code> as UTF-8/16/32 and tests if it is a <code>{</code> according to <a href="http://www.ietf.org/rfc/rfc4627.txt" rel="nofollow">RFC 4627</a> (which is referenced and updated by <a href="http://www.rfc-editor.org/rfc/rfc7159.txt" rel="nofollow">RFC 7159</a>) to determine its JSONness:</p>
  
  <blockquote>
    <p>JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.</p>
  </blockquote>
  
  <p>And:</p>
  
  <blockquote>
    <p>Since the first two characters of a JSON text will always be ASCII
       characters [RFC0020], it is possible to determine whether an octet
       stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
       at the pattern of nulls in the first four octets.</p>
  </blockquote>
  
  <pre><code>       00 00 00 xx  UTF-32BE
         00 xx 00 xx  UTF-16BE
         xx 00 00 00  UTF-32LE
         xx 00 xx 00  UTF-16LE
         xx xx xx xx  UTF-8
  </code></pre>
  
  <p>The method is:</p>
  
  <pre><code>public static boolean mightBeJSON(InputStream stream) {
      try {
          byte[] bytes = new byte[1];
  
          stream.read(bytes);
          if (bytes[0] == 0x7B) {
              return true;
          }
  
          stream.read(bytes);
          if (bytes[0] == 0x7B) {
              return true;
          }
  
          stream.read(bytes);
          stream.read(bytes);
          if (bytes[0] == 0x7B) {
              return true;
          }
      } catch (IOException e) {
          // Nothing to do;
      }
  
      return false;
  }
  </code></pre>
  
  <p>Until now my machine is still not burning, BUT:</p>
  
  <ul>
  <li>Is there anything wrong with this approach/implementation?</li>
  <li>May there be any problems in some situations?</li>
  <li>Anything to improve?</li>
  </ul>