Reputation: 1100
I'm developping an application with slim4 framework with php8.3. I installed symfony serializer to serialize/deserialise my objects.
this is how i created the serializer like a dependency:
dependencices.php
$containerBuilder->addDefinitions([
Serializer::class => function () {
$encoders = [new JsonEncoder()];
$extractors = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
$normalizers = [new ArrayDenormalizer(), new ObjectNormalizer(null, null, null, $extractors)];
return new Serializer($normalizers, $encoders);
}
]);
this is my entity:
<?php
namespace App\Domain\Entity;
use App\Application\Repository\CompanyRepository;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Table;
use Symfony\Component\Serializer\Annotation\Groups;
#[Entity(repositoryClass: CompanyRepository::class), Table(name: 'companies')]
class Company
{
#[Groups(['save-company'])]
#[Column(type: 'string', length: 9, nullable: true)]
private string $siren;
#[Groups(['save-company'])]
#[Column(type: 'string', length: 15, nullable: true)]
private string $siret;
#[Column(name: 'trading_name', type: 'string', length: 50, nullable: true)]
private ?string $tradingName;
public function getSiren(): string
{
return $this->siren;
}
public function setSiren(string $siren): void
{
$this->siren = $siren;
}
public function getSiret(): string
{
return $this->siret;
}
public function setSiret(string $siret): void
{
$this->siret = $siret;
}
public function getTradingName(): ?string
{
return $this->tradingName;
}
public function setTradingName(?string $tradingName): void
{
$this->tradingName = $tradingName;
}
}
this is how i'm deserializing my object:
$this->sfSerializer->deserialize(json_encode($this->getFormData()), Company::class, JsonEncoder::FORMAT, [
AbstractNormalizer::OBJECT_TO_POPULATE => $company,
AbstractNormalizer::GROUPS => ['save-company']
]);
this is the body of the request:
{
"siren": "SRN-1",
"siret": "SRT-1",
"tradingName": "my comany name"
}
what i want is that the serializer to deserialize only siren and siret, but it deserialize all the attributes. what i'm missing?
Upvotes: 1
Views: 213
Reputation: 109
Try using the #Ignore attribute in your entity on the field you don't want to be serialize :
#[Column(name: 'trading_name', type: 'string', length: 50, nullable: true)]
#[Ignore]
private ?string $tradingName;
Upvotes: 0