【问题标题】:JMS Serializer selective serializationJMS Serializer 选择性序列化
【发布时间】:2017-12-02 00:59:30
【问题描述】:

PHP、Symfony、JMSSerializerBundle。

我想将Organization对象内部的User对象序列化为其ID,但是当User对象属于其他对象时使用默认序列化。

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

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

是否有可能通过合理的努力?

【问题讨论】:

  • 嗨。如果有帮助,请您接受我的回答,或者在需要时提出一些更改:)

标签: php symfony serialization jmsserializerbundle jms-serializer


【解决方案1】:

您可以从序列化中排除 User 对象,并添加一个将返回用户 ID 的虚拟属性(您可以将其称为 userId、user 或任何您想要的名称)。

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

【讨论】:

  • 我为此目的创建了一个自定义类型,但在我看来,您的回答更清楚,所以我接受了它。谢谢!
  • 谢谢!您可以在原始问题中写下您的解决方案。这可能会有所帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-11-11
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多