0

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?

10
  • php.net/manual/en/function.json-encode.php ? Commented Nov 10, 2021 at 10:59
  • @SalimIbrogimov I'm aware of json_encode. But I have to use Serializer for serialization/deserialization Commented Nov 10, 2021 at 11:04
  • Since the serializer (encoder) only differentiates between iterable or object to determine the resulting json, there is no way to have a mix A as an array and B as 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) []; Commented Nov 10, 2021 at 14:35
  • Does this answer your question? PHP json_encode - JSON_FORCE_OBJECT mixed object and array output Commented Nov 10, 2021 at 14:35
  • 1
    I understand your requirements. As in the duplicate question, the original issue is caused by the MyClass::$b property being an array of objects. Not an object of 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; } Commented Nov 10, 2021 at 15:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.