Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

716
Views
How do I deserialize a JSON object - which has a nested property - to a Symfony entity?

I’m deserialising JSON to a php class (a Symfony entity) and it’s working fine, but I have a nested property in my JSON which I can’t figure out how to get into the php class.

PHP class:

class Vehicle
{
    private $make:

    /**
     * @SerializedName("meta")
     */
    private $colour;

    // with getters and setters...
}
// These 2 lines let us use the @SerializedName annotation
$metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);
$objectNormalizer = new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter);

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

$json = '
    {
        "make": "VW Golf",
        "meta": {
            "colour": "red"
        }
    }
';
$carJson = json_encode($json);

$vehicle = $serializer->deserialize(
    $carJson,
    Vehicle::class,
    'json',
);

$vehicle->getMake(); // VW Golf
$vehicle->getColour(); // ['meta' => ['colour' => 'red']]

…but that last line should return just red.

I was hoping that I could do something like @SerializedName("meta.colour") or @SerializedName("[meta][colour]") or @SerializedName("meta[colour]") but each of those resolve to null.

The Symfony docs on serialization doesn't look like it handles this (simple) case.

This Stackoverflow post also deals with nested properties, but in their example the nested property must be deserialised to another php class, not mapped to the existing php class, so that doesn't help me.

How can I get $colour equal to red when deserializing the JSON?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

A custom normalizer does the trick. Code follows.

<?php

namespace App\Serializer\Denormalizer;

use App\Entity\Vehicle;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareDenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class VehicleDenormalizer implements CacheableSupportsMethodInterface, ContextAwareDenormalizerInterface
{
    protected ObjectNormalizer $normalizer;
    protected PropertyAccessor $propertyAccessor;

    public function __construct(ObjectNormalizer $normalizer)
    {
        $this->normalizer = $normalizer;
        $this->propertyAccessor = PropertyAccess::createPropertyAccessor();
    }

    public function denormalize($data, $type, $format = null, array $context = []): Vehicle
    {
        /** @var Vehicle */
        $vehicle = $this->normalizer->denormalize($data, $type, $format, $context);

        // It's possible to directly access the values, but that requires error
        // checking. This method will return a null if it doesn't exist.
        $colour = $this->propertyAccessor->getValue($data, '[meta][colour]');
        $vehicle->setColour($colour);

        return $vehicle;
    }

    public function supportsDenormalization($data, $type, $format = null, array $context = [])
    {
        return Vehicle::class == $type;
    }

    public function hasCacheableSupportsMethod(): bool
    {
        return true;
    }
}

To use this denormalizer, you can either inject the SerializerInterface or explicitly create the serializer (code follows).

$json = '
    {
        "make": "VW Golf",
        "meta": {
            "colour": "red"
        }
    }
';
$carJson = json_encode($json);

// These 2 lines let us use the @SerializedName annotation
$metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);
$objectNormalizer = new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter);

$normalizers = [new VehicleDenormalizer($objectNormalizer)];
$serializer = new Serializer($normalizers);

/** @var Vehicle */
$vehicle = $serializer->denormalize(
    $carJson,
    Vehicle::class,
);

$vehicle->getMake(); // VW Golf
$vehicle->getColour(); // red

I'm explicitly creating the serializer because for some reason when the source data was a string and the destination was an integer, the injection method does not automatically convert the types and I get the following error:

The type of the "VehicleNo" attribute for class "App\Entity\Vehicle" must be one of "int" ("string" given).

(This code example isn't using VehicleNo as I've simplified it, but included it here to show an example of an error message where, say, Vehicle has a property $vehicleNo of type int).

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!