Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

717
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda