I would like to serialize object using the Symfony (5.3) Serializer to the following json:
{
"a": [
{"id" 8 },
{"id" 5 }
],
"b": {
"13": {
"id": 13
},
"5": {
"id": 5
},
"11": {
"id": 11
}
}
}
Serialization code looks like this
$object = new MyObject()
$object->addA(new A(8))->addA(new A(5));
$object->addB(new B(13))->addB(new B(5))->addB(new B(11));
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);
$serializer = new Serializer([
new ArrayDenormalizer(),
new DateTimeNormalizer(),
new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter, null, new ReflectionExtractor(), null, null, []),
], $[new JsonEncoder()]);
$serializer->serialize($object, 'json');
Code and example are simplified
There is no problem with a field, but I want b (and only b) should be serialized to a JSON object like in the example above. How can I do this? Do I need a custom normalizer?
Aas an array andBas an object using the serializer alone. You can force objects by using$serializer->serialize($object, 'json', ['json_encode_options' => \JSON_FORCE_OBJECT]);Otherwise, you will need to convert the iterable to an object, eg:$b = new stdClass();or$b = (object) [];MyClass::$bproperty being anarrayof objects. Not anobjectof indexed objects. You need to change it as I demonstrated in the link I provided. eg:public function addB(B $b) { $this->b->{$b->id} = $b; }