问题
In the same response i get a field as object and a field as Array, how can i correct this ?
Note i don't controle the building of my response because i'm using JMSSerializer
CODE (Edit 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();
...
}
回答1:
The JsonResponse uses json_encode to encode the values. json_encode by default will convert a php associative array to a json object, and a numerically indexed array will stay as a json array. See the PHP docs for more info on how json_encode works.
My suggestion is to format your php in the way that you want your json. if you only want arrays in your json, then you should format your php data using only numerically indexed arrays. if you only want to use objects in your json, then format your php data to only use associative arrays.
Examples:
$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
It looks like you are using an ArrayCollection, which is technically an object. If you want to convert an ArrayCollection to a simple array, the Doctrine docs show you that you can call a toArray()
method. So you would do something like this:
$arrayValue = $object->getActualites()->toArray();
There are a couple other things that you could try, but they might have unwanted side effects.
solution 1: you could try this in your entity:
public function getActualites()
{
return $this->actualites->toArray();
}
That way, whenever this method is called, it would return an array instead of array collection. This solution would be better than the next.
Solution 2: The other option is to make that variable an array itself. So in the constructor, you would have this
public function __construct()
{
$this->actualites = array();
}
I haven't tested this solution, I'm not 100% sure if Doctrine needs the Array Collection or not, but you could try as a last resort.
来源:https://stackoverflow.com/questions/23547419/fosrestbundle-jmsserializer-wrong-json-response