Josh J Josh J - 1 year ago 232
PHP Question

JMSSerializer stand alone - Annotation does not exist, or cannot be auto-loaded

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:

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');

Here is the exception

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.

I have the following libraries installed for the project via composer

"require": {
"jms/serializer": "1.0.*@dev"

Is there something obvious I am missing since I am not using the whole Doctrine 2 solution?

EDIT: my final solution was to create a bootstrap file with the following content:

// standard composer install vendor autoload magic
require dirname(__DIR__) . '/vendor/autoload.php';

// Bootstrap the JMS custom annotations for Object to Json mapping

Answer Source

I ran into the same problem and found your question through Google. Unfortunately you hadn't yet received any answers, so I had to dig in myself. :P

The thing is, Doctrine Annotations, which JMSSerializer Annotations uses, does NOT use normal PHP autoloading.

How are these annotations loaded? From looking at the code you could guess that the ORM Mapping, Assert Validation and the fully qualified annotation can just be loaded using the defined PHP autoloaders. This is not the case however: For error handling reasons every check for class existence inside the AnnotationReader sets the second parameter $autoload of class_exists($name, $autoload) to false. To work flawlessly the AnnotationReader requires silent autoloaders which many autoloaders are not. Silent autoloading is NOT part of the PSR-0 specification for autoloading.

This means you have to register the Annotation file(s) yourself:


... or the whole namespace (preferred method):

    <PROJECT ROOT> . "/vendor/jms/serializer/src");

Be careful with the path in registerAutoloadNamespace. I first tried to register the whole path to annotations in the same manner with registerFile:

<PROJECT ROOT> . "/vendor/jms/serializer/src/JMS/Serializer/Annotation 

but that failed miserably. :D

I hope this gets you a step further. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download