【问题标题】:FOSRestBundle & JMSSerializer : Wrong Json Response [closed]FOSRestBundle 和 JMSSerializer:错误的 Json 响应 [关闭]
【发布时间】:2014-06-26 04:17:25
【问题描述】:

在同一个响应中,我得到一个作为对象的字段和一个作为数组的字段,我该如何纠正这个?

注意我无法控制响应的构建,因为我使用的是 JMSSerializer

代码(编辑 1)

\Entity\Profil.php

       class Profil
        {

        ...
        /**
             * Get actualites
             *
             * @return \Doctrine\Common\Collections\Collection 
             */
            public function getActualites()
            {
                return $this->actualites;
            }
...
/**
     * Add actualites
     *
     * @param \Genius\ProfileBundle\Entity\Actualite $actualites
     * @return Profil
     */
    public function addActualite(\Genius\ProfileBundle\Entity\Actualite $actualites)
    {
        $this->actualites[] = $actualites;

        return $this;
    }


    ...
    public function __construct()
        {
...         
         $this->actualites = new \Doctrine\Common\Collections\ArrayCollection();
...
        }

【问题讨论】:

  • 我需要actualites字段始终是一个数组
  • 为了更好地回答您的问题,您必须展示您正在使用的某种代码。
  • 你在哪里返回 JsonResponse?
  • @Sehael by return $this->container->get('genius_profile.actualite.handler')->all($limit, $offset); 我基于的教程(参考:welcometothebundle.com/symfony2-rest-api-the-best-2013-way
  • 您调用的 all() 函数是什么?

标签: php symfony fosrestbundle jmsserializerbundle


【解决方案1】:

JsonResponse 使用 json_encode 对值进行编码。默认情况下,json_encode 会将 php 关联数组转换为 json 对象,数字索引数组将保留为 json 数组。有关 json_encode 工作原理的更多信息,请参阅PHP docs

我的建议是以你想要的 json 的方式格式化你的 php。如果您只想要 json 中的数组,那么您应该只使用数字索引数组来格式化您的 php 数据。如果您只想在 json 中使用对象,则将 php 数据格式化为仅使用关联数组。

例子:

$a = array(1,2,3);
echo json_encode($a); // [1,2,3] array output in json

$b = array('a'=>1, 'b'=>2, 'c'=>3);
echo json_encode($b); // {a:1,b:2,c:3} object output in json

看起来您正在使用 ArrayCollection,它在技术上是一个对象。如果要将 ArrayCollection 转换为简单数组,Doctrine docs 会告诉您可以调用 toArray() 方法。所以你会做这样的事情:

$arrayValue = $object->getActualites()->toArray();

您还可以尝试其他一些方法,但它们可能会产生不必要的副作用。

解决方案 1: 你可以在你的实体中试试这个:

public function getActualites()
{
    return $this->actualites->toArray();
}

这样,每当调用此方法时,它都会返回一个数组而不是数组集合。这个解决方案会比下一个更好。

解决方案 2: 另一种选择是使该变量本身成为一个数组。所以在构造函数中,你会有这个

public function __construct()
{       
     $this->actualites = array();
}

我还没有测试过这个解决方案,我不能 100% 确定 Doctrine 是否需要数组集合,但你可以作为最后的手段尝试。

【讨论】:

  • 我不控制我的阵列的构建
  • @Abdellah SELASSI:那你在寻找什么样的答案?
  • @zerkms 一个解决我问题的答案 :=)
  • @Abdellah SELASSI:这个答案提供了足够的信息来解决它
  • @Abdellah SELASSI:这个问题实际上与它无关。但是,是的,我有
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
相关资源
最近更新 更多