使用 JMS 序列化程序将实体关系仅序列化为 Id

2022-08-30 16:25:31

我正在尝试使用 JMS 序列化程序序列化实体关系。

下面是实体:

class Ad
{ 

    /**
     * @Type("string")
     * @Groups({"manage"})
     * 
     * @var string
     */
    private $description;

    /**
     * @Type("Acme\SearchBundle\Entity\Country")
     * @Groups({"manage"})
     * 
     * @var \Acme\SearchBundle\Entity\Country
     */
    private $country;

    /**
     * @Type("string")
     * @Groups({"manage"})
     * 
     * @var string
     */
    private $title;

    /**
     * Set description
     *
     * @param string $description
     * @return Ad
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set country
     *
     * @param \Acme\SearchBundle\Entity\Country $country
     * @return Ad
     */
    public function setCountry($country)
    {
        $this->country= $country;

        return $this;
    }

    /**
     * Get country
     *
     * @return string 
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Ad
     */
    public function setTituloanuncio($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string 
     */
    public function getTitle()
    {
        return $this->title;
    }

}

和关系的实体:

class Country
{

    /**
     * @Type("string")
     * @Groups("manage")
     * 
     * @var string
     */
    private $id;

    /**
     * @Type("string")
     * @Groups("admin")
     * 
     * @var string
     */
    private $description;

    /**
     * Set description
     * @Groups("")
     *
     * @param string $description
     * @return Country
     */
    public function setDescripcionpais($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    {
        return $this->description;
    }

    }

    /**
     * Get id
     *
     * @return string 
     */
    public function getId()
    {
        return $this->id;
    }
}

我序列化实体,但我不知道如何将国家/地区属性转换为简单字段。

我在 json 中得到这个结果:

{"description":"foo", "title":"bar", "country":{"id":"en"} }

但是我想像这样获取该国的id字段:

{"description":"foo", "title":"bar", "country": "en" }

使用 JMS 序列化程序是否可行?

谢谢。

[编辑]

@VirtualProperty不起作用。


答案 1

是的,您可以使用注释:@VirtualProperty

/**
 * @VirtualProperty
 * @SerializedName("foo")
 */
public function bar()
{
    return $this->country->getCode();
}

但是,当涉及到反序列化时,请注意:

@VirtualProperty可以在方法上定义此批注,以指示该方法返回的数据应显示为对象的属性。

> 注意:这仅适用于序列化,在反序列化过程中完全忽略。

希望这有帮助...


答案 2

只是为了遵循回答的问题:

如果您不喜欢为每个关系编写一个方法 - 只需编写自己的处理程序即可。这很容易像

final class RelationsHandler
{
    /**
     * @var EntityManagerInterface
     */
    private $manager;

    /**
     * RelationsHandler constructor.
     *
     * @param EntityManagerInterface $manager
     */
    public function __construct(EntityManagerInterface $manager) { $this->manager = $manager; }


    public function serializeRelation(JsonSerializationVisitor $visitor, $relation, array $type, Context $context)
    {
        if ($relation instanceof \Traversable) {
            $relation = iterator_to_array($relation);
        }

        if (is_array($relation)) {
            return array_map([$this, 'getSingleEntityRelation'], $relation);
        }

        return $this->getSingleEntityRelation($relation);
    }

    /**
     * @param $relation
     *
     * @return array|mixed
     */
    protected function getSingleEntityRelation($relation)
    {
        $metadata = $this->manager->getClassMetadata(get_class($relation));

        $ids = $metadata->getIdentifierValues($relation);
        if (!$metadata->isIdentifierComposite) {
            $ids = array_shift($ids);
        }

        return $ids;
    }
}

注册处理程序

  jms_serializer.handler.relation:
      class: MyBundle\RelationsHandler
      arguments:
      - "@doctrine.orm.entity_manager"
      tags:
      - { name: jms_serializer.handler, type: Relation, direction: serialization, format: json, method: serializeRelation}
      - { name: jms_serializer.handler, type: Relation, direction: deserialization, format: json, method: deserializeRelation}
      - { name: jms_serializer.handler, type: Relation<?>, direction: serialization, format: json, method: serializeRelation}
      - { name: jms_serializer.handler, type: Relation<?>, direction: deserialization, format: json, method: deserializeRelation}

这允许您将虚拟 getter 方法替换为 'Type(“Relation”)。

如果您还不想反序列化关系 - 您应该告诉每个类名()它应该反序列化到哪个,或者用一个为您执行此操作的类名包装元数据驱动程序。@Type("Relation")@Type("Relation<FQCN>")

    public function deserializeRelation(JsonDeserializationVisitor $visitor, $relation, array $type, Context $context)
    {
        $className = isset($type['params'][0]['name']) ? $type['params'][0]['name'] : null;

        if (!class_exists($className, false)) {
            throw new \InvalidArgumentException('Class name should be explicitly set for deserialization');
        }

        $metadata = $this->manager->getClassMetadata($className);

        if (!is_array($relation)) {
            return $this->manager->getReference($className, $relation);
        }

        $single = false;
        if ($metadata->isIdentifierComposite) {
            $single = true;
            foreach ($metadata->getIdentifierFieldNames() as $idName) {
                $single = $single && array_key_exists($idName, $relation);
            }
        }

        if ($single) {
            return $this->manager->getReference($className, $relation);
        }

        $objects = [];
        foreach ($relation as $idSet) {
            $objects[] = $this->manager->getReference($className, $idSet);
        }

        return $objects;
    }

推荐