@@ -503,6 +503,22 @@ The Symfony templating engine is explained in great detail in the
503
503
.. index ::
504
504
single: Controller; Accessing services
505
505
506
+ Sending JSON responses
507
+ ~~~~~~~~~~~~~~~~~~~~~~
508
+
509
+ If you're developing an API, you'll probably return JSON contents from your
510
+ controllers. The ``json() `` method turns the given contents into JSON format and
511
+ prepares the HTTP response accordingly for you::
512
+
513
+ // returns '{"username":"jane.doe"}' and sets the proper Content-Type header
514
+ $data = array('username' => 'jane.doe');
515
+ return $this->json($data);
516
+
517
+ The only required argument is the data to be sent, but ``json() `` defines three
518
+ more optional arguments::
519
+
520
+ $this->json($data, $status = 200, $headers = array(), $context = array());
521
+
506
522
.. _controller-accessing-services :
507
523
508
524
Accessing other Services
@@ -774,24 +790,6 @@ There are also special classes to make certain kinds of responses easier:
774
790
:class: `Symfony\\ Component\\ HttpFoundation\\ StreamedResponse `.
775
791
See :ref: `streaming-response `.
776
792
777
- JSON helper
778
- ~~~~~~~~~~~
779
-
780
- You can simplify sending JSON response with
781
- :method: `Symfony\\ Bundle\\ FrameworkBundle\\ Controller\\ Controller::json `
782
- helper::
783
-
784
- $this->json($data, $status = 200, $headers = array(), $context = array());
785
-
786
- For example if you want to send some simple array you can use it like this::
787
-
788
- public function jsonAction()
789
- {
790
- $data = [1, 2, 3];
791
-
792
- return $this->json($data);
793
- }
794
-
795
793
.. seealso ::
796
794
797
795
Now that you know the basics you can continue your research on Symfony
0 commit comments