Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is where a build in way to deserialize nested object with type hint property?

I am trying to convert data from json to DTO class. I am using Symfony serializer.

But when I am trying to deserialize. It does not parse type from typed property, I guess Symfony does not support deserialization form typed property yet. Is it so? Do I have to implement my one?

DTO:

class ElkUser
{
    public string     $partnerUuid;
    public string     $contractUuid;
    public DealerInfo $dealerInfo;
}

class DealerInfo
{
    public string $description;
    public int $dealerId;
    public string $dealerName;
    public bool $enabled;
    public string $registrationDate;
}

Serializer config:

$normalizers = [
    new DateTimeNormalizer(),
    new ObjectNormalizer(
        null,
        null,
        null,
        new ReflectionExtractor
    ),

];

$serializer new Serializer($normalizers, [new JsonEncoder()]);

The test case when give me error:

TypeError : Typed property App\Services\CreditPilot\ElkUser::$dealerInfo must be an instance of App\Services\CreditPilot\DealerInfo, array used

$json = <<< JSON
{
  "partnerUuid": "string",
  "contractUuid": "string",
  "dealerInfo": {
    "dealerId": 0,
    "dealerName": "string",
    "enabled": true,
    "registrationDate": "2020-03-10T12:49:08.367Z",
    "contract": {
      "contractNumber": "string",
      "enabled": true,
      "creationDate": "2020-03-10T12:49:08.367Z"
    }
  }
}
JSON;

$serializer->deserialize($json, ElkUser::class, 'json');

like image 992
112Legion Avatar asked Mar 10 '20 12:03

112Legion


1 Answers

This will be supported natively in Symfony 5.1:

The PropertyInfo component extracts information about the properties of PHP classes using several sources (Doctrine metadata, PHP reflection, PHPdoc config, etc.) In Symfony 5.1, we improved this component to also extract information from PHP typed properties.

Before that, you need to give some information to the serializer so it's able to infer the type. A PhpDoc or a typed setter could be enough.

like image 133
yivi Avatar answered Sep 21 '22 23:09

yivi