I'm trying to use JMS Serializer on a new PHP 8 project and somehow I'm not able to get any of the annotations to work. This is my simplified settings:
composer.json
{
"require": {
"jms/serializer": "^3.32"
}
}
test.php
<?php
require_once __DIR__.'/vendor/autoload.php';
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\SerializerBuilder;
/** @ExclusionPolicy("all") */
class Test {
/** @Expose */
private string $name;
private int $value;
public function getName(): string {
return $this->name;
}
public function setName(string $name): void {
$this->name = $name;
}
public function getValue(): int {
return $this->value;
}
public function setValue(int $value): void {
$this->value = $value;
}
}
$test = new Test();
$test->setName("John Doe");
$test->setValue(100);
$serializer = SerializerBuilder::create()->build();
echo $serializer->serialize($test, 'json');
If I execute the code above the output is the following:
{"name":"John Doe","value":100}
Instead I was expecting to see:
{"name":"John Doe"}
I also tried a million of combinations of other annotation, and no one seem to work. Any clues? Many thanks in advance!
Use PHP8 Attributes. Then it works. Annotations have been optional since 3.30.0. If you install doctrine/annotations
, it should also work with annotations. See documentation.
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
#[ExclusionPolicy("all")]
class Test
{
#[Expose]
private string $name;
/* ... */
}