简体   繁体   中英

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?

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(); 
   }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM