从Symfony中的Controller返回一个JSON数组

时间:2015-01-25 20:37:42

标签: php json symfony

我正在尝试从Symfony 2中的控制器返回JSON响应。表单示例,在Spring MVC中,我可以使用@ResponseBody annotattion获取JSON响应。我想得到一个JSON响应,如果它是一个JSON数组或一个Json对象,则没有mtter,然后在视图中用javascript操作它。

我尝试下一个代码:

/**
     * @Route(
     *      "/drop/getCategory/",
     *      name="getCategory"
     * )
     * @Method("GET")
     */
    public function getAllCategoryAction() {
        $categorias = $this->getDoctrine()
                           ->getRepository('AppBundle:Categoria')
                           ->findAll();

        $response = new JsonResponse();
        $response->setData($categorias);

        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

但我在浏览器中将[{},{}]作为Response。我也尝试使用$response = new Response(json_encode($categorias));,但我得到的结果相同。

7 个答案:

答案 0 :(得分:15)

我认为@darkangelo的答案需要解释。

findAll()方法返回一组对象。

$categorias = $this->getDoctrine()
                   ->getRepository('AppBundle:Categoria')
                   ->findAll();

要构建您的回复,您必须将实体的所有获取者添加到您的回复中,例如:

$arrayCollection = array();

foreach($categorias as $item) {
     $arrayCollection[] = array(
         'id' => $item->getId(),
         // ... Same for each property you want
     );
}

return new JsonResponse($arrayCollection);

使用QueryBuilder可以将结果作为包含所有属性的数组返回:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
    'SELECT c
    FROM AppBundle:Categoria c'
);
$categorias = $query->getArrayResult();

return new JsonResponse($categorias);

getArrayResult()避免需要吸气剂。

答案 1 :(得分:13)

您需要这样做(根据之前的回答):

public function getAllCategoryAction() {
    $em = $this->getDoctrine()->getManager();
    $query = $em->createQuery(
        'SELECT c
        FROM AppBundle:Categoria c'
    );
    $categorias = $query->getArrayResult();

    $response = new Response(json_encode($categorias));
    $response->headers->set('Content-Type', 'application/json');

    return $response;
}

它适用于Doctrine作为数组返回的任何Query。

答案 2 :(得分:1)

您需要以这种方式更改代码:

/**
 * @Route(
 *      "/drop/getCategory/",
 *      name="getCategory"
 * )
 * @Method("GET")
 */
public function getAllCategoryAction() {
    $categorias = $this->getDoctrine()
                       ->getRepository('AppBundle:Categoria')
                       ->findAll();

    $categorias = $this->get('serializer')->serialize($categorias, 'json');

    $response = new Response($categorias);

    $response->headers->set('Content-Type', 'application/json');
    return $response;
}

如果未启用serializer服务,您必须在app/config/config.yml中启用它:

    framework:
        # ...
        serializer:
            enabled: true

有关序列化的更高级选项,您可以安装JMSSerializerBundle

答案 3 :(得分:1)

看起来你正试图回应一个集合。为此,您需要设置序列化程序(或将数据检索为数组)。

请查看此文档页面:http://symfony.com/doc/current/components/http_foundation/introduction.html#creating-a-json-response

http://symfony.com/doc/current/cookbook/serializer.html

答案 4 :(得分:1)

按照最佳做法,我设法通过以下方式做到这一点:

loop

注入存储库和序列化器。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randint
from numpy.random import randint

pd.set_option('display.max_colwidth', 0)

df = pd.read_csv('LDD Permissions for Datastore - Final selected updated 19.04.2020 - including checked05.05 -used.csv', encoding='mac_roman')

#Aggregate the sum of net additional units by Permission Fianacial Year and Planning Authority
pd.set_option('display.max_rows', 1000)
total_permitted_unit_per_year = df.groupby(['Permission Financial Year','Planning Authority']).sum()['Net additional units'].unstack(-1)

#Generate subplots of net additional units from 2009 to 2019 for each Planning Authority
plt.rc('xtick',labelsize=10)
plt.rc('ytick',labelsize=10)

fig = plt.figure()
plt.figure(figsize=(200, 800))

ax1 = fig.add_subplot(7,5,1)
ax2 = fig.add_subplot(7,5,2)
ax3 = fig.add_subplot(7,5,3)
ax4 = fig.add_subplot(7,5,4)
ax5 = fig.add_subplot(7,5,5)
ax6 = fig.add_subplot(7,5,6)
ax7 = fig.add_subplot(7,5,7)
ax8 = fig.add_subplot(7,5,8)
ax9 = fig.add_subplot(7,5,9)
ax10 = fig.add_subplot(7,5,10)
ax11 = fig.add_subplot(7,5,11)
ax12 = fig.add_subplot(7,5,12)

total_permitted_unit_per_year.plot(y='Barking and Dagenham', ax=ax1, legend=False, marker='.', markersize=5, figsize=(30,15))
ax1.set_title('Barking and Dagenham')
ax1.set_ylim([0, 350])

total_permitted_unit_per_year.plot(y='Barnet', ax=ax2, legend=False, marker='.', markersize=5, figsize=(30,15))
ax2.set_title('Barnet')
ax2.set_ylim([0, 350])

total_permitted_unit_per_year.plot(y='Bexley', ax=ax3, legend=False, marker='.', markersize=5, figsize=(30,15))
ax3.set_title('Bexley')
ax3.set_ylim([0, 350])

total_permitted_unit_per_year.plot(y='Sutton', ax=ax4, legend=False, marker='.', markersize=5, figsize=(30,15))
ax4.set_title('Sutton')
ax4.set_ylim([0, 350])

total_permitted_unit_per_year.plot(y='Merton', ax=ax5, legend=False, marker='.', markersize=5)
ax5.set_title("Merton")
ax5.set_ylim([0, 350])

检索对象数组。

letters.map

将数据序列化为JSON字符串。

public function index(CityRepository $cityRepository,
                      SerializerInterface $serializer): Response 

将JSON字符串传递到$cities = $cityRepository->findAll();

答案 5 :(得分:1)

/**
 * @Route("/api/list", name="list")
 */
public function getList(SerializerInterface $serializer, SomeRepository $repo): JsonResponse
{
    $models = $repo->findAll();
    $data = $serializer->serialize($models, JsonEncoder::FORMAT);
    return new JsonResponse($data, Response::HTTP_OK, [], true);
}

答案 6 :(得分:0)

我建议采用以下解决方案:

/**
     * @Route(
     *      "/drop/getCategory/",
     *      name="getCategory"
     * )
     * @Method("GET")
     */
    public function getAllCategoryAction() {
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery(
            'SELECT c
            FROM AppBundle:Categoria c'
        );
        $categorias = $query->getArrayResult();


        return new Response(json_encode($categorias), 200);
}