Mac_Cain13
Mac_Cain13

Reputation: 3633

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!

Upvotes: 3

Views: 2541

Answers (2)

Jorj
Jorj

Reputation: 2701

Don't use "double" as column type because you risk having malformed representation of the coordinates. Better cast your attribute:

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

Upvotes: 0

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

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;

Upvotes: 6

Related Questions