在Symfony中序列化和反序列化UUID对象

时间:2020-01-13 16:48:28

标签: symfony4 uuid json-deserialization

我正在尝试将对象序列化为JSON,然后反序列化它们。我为所有ID使用ramsey / uuid。

/**
 * NotificationService constructor.
 */
public function __construct(ObjectManager $manager, EntityManagerInterface $entityManager, SerializerInterface $serializer)
{
    $this->manager = $manager;
    $this->entityManager = $entityManager;
    $this->pollRepository = $this->entityManager->getRepository(Poll::class);
    $this->threadRepository = $this->entityManager->getRepository(ForumThread::class);
    $this->notificationRepository = $this->entityManager->getRepository(Notification::class);
    $this->serializer = $serializer;
}

/**
 * @param $objectToSerialize
 *
 * @return string
 */
public function jsonEncode($objectToSerialize)
{
    // Serialize my object in Json
    return $this->serializer->serialize($objectToSerialize, 'json', [
        'circular_reference_handler' => function ($object) {
            return $object->getId();
        },
    ]);
}

/**
 * @param $json
 * @param $class
 *
 * @return mixed
 */
public function jsonDecode($json, $class)
{
    return $this->serializer->deserialize($json, $class, 'json');
}

我的函数jsonEncode正常工作。但是第二个jsonDecode向我显示了此错误:

Symfony\Component\Serializer\Exception\NotNormalizableValueException

The type of the "id" attribute for class "App\Entity\Poll" must be one of "Ramsey\Uuid\UuidInterface" ("string" given).

感谢您的帮助

0 个答案:

没有答案