title: Return JSON based on "Accept: application/json" from a Symfony2 controller
body: <p>I've got a CRUD form generated via the SensioGeneratorBundle, as <a href="https://stackoverflow.com/questions/16695463/is-there-a-facility-for-generating-scaffolding-in-a-symfony2-app">described here</a>.  This works great.</p>
  
  <p>However, I would like to also return JSON, rather than HTML responses, if the "Accept" HTTP header contains only "application/json".  I'm working on a prototype for a JSON service and this would help me jump start things.</p>
  
  <p>I figured out that I can turn my entities into a JSON string like this:</p>
  
  <pre><code>use Symfony\Component\Serializer\Serializer;
  use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
  use Symfony\Component\Serializer\Encoder\JsonEncoder;
  
  $serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' =&gt; new 
  JsonEncoder()));
  $json = $serializer-&gt;serialize($entity, 'json');
  </code></pre>
  
  <p>However, at the end of that, $json contains a string that is my JSON data.  I want to just directly output that to the requestor, rather than render the usual view.  I've tried returning a new JsonResponse($json), but it re-encodes the JSON string, so it winds up double-encoded.</p>
  
  <p>So I have two questions:</p>
  
  <ol>
  <li>What is the "correct" way to inspect the HTTP requestion headers?  I know I can just look in $_SERVER, but I'm thinking that there may be a better way to do this in Symfony2.</li>
  <li>What is the "correct" way to return a JSON string, or to translate my entities into JSON that is returned straight to the requestor, without rendering the usual view.</li>
  </ol>
  
  <p>Thanks!</p>