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?