Question

As a simple example I have a doctrine entity with the following fields

id
name
description

I am using JMSSerializerBundle and it is working well in most cases, however what if I wanted to have the serialized data (the Json) include something that is not mapped exactly to my entity.

For example, what if I only wanted the first 50 characters of the description returned and I wanted to call that short_description.

I tried to use the Exclusion Strategies with @Expose to expose a method, but this is not supported.

I will need to do this kind of thing frequently and with many different entities, I was wondering if anyone could suggest a nice clean approach to this.

I have read the entire documentation of JMSSerializerBundle and also looked for solutions on the internet, I can think up some solutions but the resulting code looks a bit dirty.

Was it helpful?

Solution

The annotation @VirtualProperty is what you are looking for (http://jmsyst.com/libs/serializer/master/reference/annotations#virtualproperty).

For example:

namespace Some\Bundle\Entity;

use JMS\Serializer\Annotation\VirtualProperty;
use JMS\Serializer\Annotation\SerializedName;

class MyEntity
{
     private $description;

     /**
      * @VirtualProperty
      * @SerializedName("short_description")
      */
     public function getShortDescription()
     {
         return substr($this->description, 0, 50);
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top