JMSSerializer独立-注释不存在,或者无法自动加载 [英] JMSSerializer stand alone - Annotation does not exist, or cannot be auto-loaded
问题描述
我试图将JMSSerializer用作独立的库,以将JSON响应从API映射到我的模型类,并且遇到了一些问题.
I am attempting to use JMSSerializer as a stand alone library to map JSON responses from an API to my model classes and am running into some issues.
执行以下代码会导致异常:
Executing the following code results in an exception:
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use JMS\Serializer\Annotation AS JMS;
class Trii {
/**
* User ID for this session
* @JMS\SerializedName("userID")
* @JMS\Annotation(getter="getUserId")
* @JMS\Type("string")
* @var string
*/
private $userId;
public function getUserId() {
return $this->userId;
}
public function setUserId($userId) {
$this->userId = $userId;
}
}
$serializer = \JMS\Serializer\SerializerBuilder::create()->setDebug(true)->build();
$object = $serializer->deserialize('{"userID":"Trii"}', 'Trii', 'json');
var_dump($object);
?>
这是个例外
Doctrine\Common\Annotations\AnnotationException: [Semantical Error] The annotation "@JMS\Serializer\Annotation\SerializedName" in property Trii::$userId does not exist, or could not be auto-loaded.
我通过composer为项目安装了以下库
I have the following libraries installed for the project via composer
{
"require": {
"jms/serializer": "1.0.*@dev"
}
}
因为我没有使用整个《 Doctrine 2》解决方案,我是否缺少明显的东西?
Is there something obvious I am missing since I am not using the whole Doctrine 2 solution?
我的最终解决方案是创建一个具有以下内容的引导文件:
my final solution was to create a bootstrap file with the following content:
<?php
// standard composer install vendor autoload magic
require dirname(__DIR__) . '/vendor/autoload.php';
// Bootstrap the JMS custom annotations for Object to Json mapping
\Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace(
'JMS\Serializer\Annotation',
dirname(__DIR__).'/vendor/jms/serializer/src'
);
?>
推荐答案
可以肯定,这将启用静默自动加载,这比自己注册名称空间要方便得多.
Pretty sure this enables silent auto-loading which is much more convenient than registering the namespaces yourself.
AnnotationRegistry::registerLoader('class_exists');
这篇关于JMSSerializer独立-注释不存在,或者无法自动加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!