MB.
MB.

Reputation: 723

Symfony Deserialization of CSV data into Array of objects

I have a php class with one property that uses DateTimeInterface. the other properties are string, int, etc.

php class

#[ORM\Column(type: Types::DATE_MUTABLE)]
private ?\DateTimeInterface $eff_date = null;

In my Controller I process some CSV data to populate the class (header row followed by multiple data rows). I setup the serializer like so.

   $encoders = [new CsvEncoder()];
    $normalizers = [new ObjectNormalizer(), new DateTimeNormalizer()];
    $serializer = new Serializer($normalizers, $encoders);

Two step process works mostly (single deserialize step does not work)

  1. decode step
  2. denormalize step
    $output = $serializer->decode($data,'csv');
    dump($output);
    
    $an_object_array = [];
    
    foreach($output as $item) { //foreach element in $arr
            $an_object = $serializer->denormalize($item, Rmk::class);
            $an_object_array[] = $an_object;
    }
    
    dd($an_object_array);

If I set the property as a string the serialization works fine.

if not I get the following error.

Failed to denormalize attribute "EFF_DATE" value for class "App\Entity\Rmk": Expected argument of type "?DateTimeInterface", "string" given at property path "EFF_DATE".

Upvotes: 1

Views: 2177

Answers (1)

MB.
MB.

Reputation: 723

found the solution.

  1. changed the setter method in the entity to accept string as input and create a date time object from the string.

  2. corrected normalizers

    $normalizers = array(
        new ObjectNormalizer(),
        new ArrayDenormalizer(),
    );
  1. switched to single deserialize step also.
    $remarks = $serializer->deserialize($data, Rmk::class.'[]','csv');

Upvotes: 1

Related Questions