Search code examples
phpsymfonyserializationjmsserializerbundlejms-serializer

JMS Serializer selective serialization


PHP, Symfony, JMSSerializerBundle.

I want to serialize the User object inside Organization object to its ID, but when the User object belongs to other objects use default serialization.

public class Organization {
   // type is User   
   $user;  -> "123123"
...
}

public class Other {
   // type is User   
   $user;  -> "{id: 123123, name: John, ...}"
...
}

Is it possible with reasonable effort?


Solution

  • You could exclude User object from serialization, and add a virtual property that will return user ID (you can call it userId, user or whatever you want).

    use JMS\Serializer\Annotation\VirtualProperty;
    use JMS\Serializer\Annotation\Exclude;
    
    public class Organization {
    
       /**
        * ...
        * @Exclude
        */ 
        $user;
    
      /**
       * @VirtualProperty
       * @SerializedName("user")
       */
       public function getUserId()
       { 
          return $this->user->getId(); 
       }
        ...
    }