title: Return JSON based on “Accept: application/json” from a Symfony2 controller without modifying each controller action
body: <p>I'm working on an app that I want to offer both JSON and HTML responses.  Here's an example action method:</p>
  
  <pre><code>/**
   * Lists all Boards entities.
   *
   * @Route("/", name="boards")
   * @Method("GET")
   * @Template()
   */
  public function indexAction()
  {
      $em = $this-&gt;getDoctrine()-&gt;getManager();
  
      $entities = $em-&gt;getRepository('ScrumBoardServiceBundle:Boards')-&gt;findAll();
  
      $acceptHeader = strtolower($this-&gt;getRequest()-&gt;headers-&gt;get('Accept'));
      if ($acceptHeader === 'application/json') {
          $serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' =&gt; new
                  JsonEncoder()));
          $response = $serializer-&gt;serialize(array('success' =&gt; true, 'data' =&gt; array(
                  'entity' =&gt; $entities,
          )), 'json');
          $result = new Response($response, 200, array('Content-Type' =&gt; 'application/json'));
      } else {
          $result = array(
              'entities' =&gt; $entities,
          );
      }
  
      return $result;
  }
  </code></pre>
  
  <p>This works fine.  If you send in an HTTP Accept header that is <em>exactly</em> <code>application/json</code>, you will get JSON back.  Otherwise, you get the usual hTML view.</p>
  
  <p>This works fine, but I've got dozens of actions.  I'd rather not repeat myself.  I'm working on refactoring this code into something a little more generic... but I'm also wondering if this problem has already been solved by an existing Symfony2 bundle.  Maybe something with annotations?  Or a config setting?  I haven't been able to find anything so far.  But I am so new to Symfony I could very easily be missing something.</p>