php 从 Symfony 中的控制器返回一个 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28141192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:42:59  来源:igfitidea点击:

Return a JSON array from a Controller in Symfony

phpjsonsymfony

提问by Giancarlo Ventura Granados

I am trying return a JSON response from a controller in Symfony 2. Form example, in Spring MVC I can get a JSON response with @ResponseBody annotattion. I want get a JSON response, no mtter if it is a JSON Array or a Json Object, then, manipulate it with javascript in the view.

我正在尝试从 Symfony 2 中的控制器返回 JSON 响应。表单示例,在 Spring MVC 中,我可以使用 @ResponseBody 注释获得 JSON 响应。我想要一个 JSON 响应,不管它是 JSON 数组还是 Json 对象,然后在视图中使用 javascript 操作它。

I try the next code:

我尝试下一个代码:

/**
     * @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;
    }

But I get [{},{}]as Response in the browser. I try with $response = new Response(json_encode($categorias));too, but I get the same result.

但我[{},{}]在浏览器中得到响应。我也尝试$response = new Response(json_encode($categorias));过,但我得到了相同的结果。

回答by chalasr

I think the @darkangelo answer need explainations.

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

The findAll()method return a collection of objects.

findAll()方法返回对象的集合。

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

To build your response, you have to add all getters of your entities to your response like :

要构建您的响应,您必须将实体的所有 getter 添加到您的响应中,例如:

$arrayCollection = array();

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

return new JsonResponse($arrayCollection);

Use QueryBuilderallows you to return results as arrays containing all properties :

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

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

return new JsonResponse($categorias);

The getArrayResult()avoids need of getters.

getArrayResult()避免了需要干将。

回答by darkangelo

You need to do this (based on previous answer):

您需要这样做(基于先前的答案):

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;
}

It works perfect with any Query that Doctrine returns as array.

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

回答by Alexandru Furculita

You need to change your code this way:

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

/**
 * @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;
}

If the serializerservice is not enabled, you have to enable it in app/config/config.yml:

如果该serializer服务未启用,则必须在以下位置启用它app/config/config.yml

    framework:
        # ...
        serializer:
            enabled: true

For more advanced options for serialization, you can install JMSSerializerBundle

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

回答by Alex

Looks like you are trying to put into response a collection. For that you need to setup serializer (or retrieve data as an array).

看起来您正在尝试响应一个集合。为此,您需要设置序列化程序(或以数组形式检索数据)。

Look at this doc pages: http://symfony.com/doc/current/components/http_foundation/introduction.html#creating-a-json-response

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

and

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

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

回答by Jan Bodnar

Following the best practices, I managed to do it the following way:

遵循最佳实践,我设法通过以下方式做到了:

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

Injecting repository & serializer.

注入存储库和序列化程序。

$cities = $cityRepository->findAll();

Retrieving an array of objects.

检索对象数组。

$data = $serializer->serialize($cities, 'json');

Serializing the data into a JSON string.

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

return new JsonResponse($data, 200, [], true);

Passing the JSON string to JsonResponse.

将 JSON 字符串传递给JsonResponse.

回答by AlexS

/**
 * @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);
}

回答by Giancarlo Ventura Granados

I suggest the following solution:

我建议以下解决方案:

/**
     * @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);
}