Mac_Cain13 Mac_Cain13 - 3 months ago 19
PHP Question

JMSSerializerBundle is returning doubles as strings in JSON

So we're using the

JMSSerializerBundle
in our Symfony2 project to generate some JSON for our clients. It's serializing our Doctrine2 entities and works like charm, with one exception. All doubles/decimal values are strings in the resulting JSON and this is confusing the clients.

Our serialized entity looks like this, I've only pasted the relevant attributes/getters here.

class Offer
{
[...]

/**
* @var double $latitude
*
* @ORM\Column(name="latitude", type="decimal", precision=10, scale=7)
* @Groups("offerlist")
*/
private $latitude;

/**
* @var double $longitude
*
* @ORM\Column(name="longitude", type="decimal", precision=10, scale=7)
* @Groups("offerlist")
*/
private $longitude;

[...]

/**
* Get latitude
*
* @return double
*/
public function getLatitude()
{
return $this->latitude;
}

/**
* Get longitude
*
* @return double
*/
public function getLongitude()
{
return $this->longitude;
}

[...]
}


The latitude/longitude values show up in the JSON like this:

{
"latitude" : "5.3452",
"longitude" : "54.2312"
}


How do I get rid of the quotes, so it's a number in the JSON and not a string? This should be really easy, but I can't find anything in the docs or online about this problem. Hope someone can give me a hand here!

Answer

Your latitude and longitude columns are using Doctrine's decimal type, which is represented as a string.

You could use Doctrine's double type if you can:

/**
 * ...
 * @ORM\Column(name="latitude", type="double")
 */
private $latitude;

or use JMSSerializerBundle's @Type annotation:

/**
 * ...
 * @Serializer\Type("double")
 */
private $latitude;
Comments