Deserialize array of object using jms/serializer
Asked Answered
H

2

12

I want to deserialize something like this:

[
    { "id": 42 },
    { "id": 43 }
]

Any idea how to do this?

Hydric answered 11/6, 2017 at 8:53 Comment(5)
I read all the documentation and did not find any this for this... The only solution I found is to create an other class a do something like this: @Type("array<Class>") but it does not work since the array should have a key to workHydric
So if it doesn't belong to an entity, its just json - so what is wrong with using php's json_decode?Bog
The goal of using jms/serializer is to transforme json string into your objects, not stdClass like when using json_decodeHydric
$serializer->deserialize($json, 'array<T>', 'json'); ? Where T is the type with id property.Passbook
Almost, but thanks ! It work with deserialize($json, "array<Class>") you can post the answer if you want.Hydric
P
36

It would be

$serializer->deserialize($json, 'array<T>', 'json')

where T is the name of the class with the id property.

Passbook answered 11/6, 2017 at 21:42 Comment(2)
Is there a way to preserve keys (ex: [123=> { "id": 42 }, 234=>{ "id": 42 }] ) within the array? This worked for me but the keys are reset (starting from 0)Otto
Figured it out: $this->serializer->deserialize($result, 'array<integer,MyModelDefinedInYML>>', 'json')Otto
U
1

Let's say you have a class foo, that has an attribute with an array of bar objects.

In your foo class use JMS\Serializer\Annotation\Type as Type; and annotate the attribute like this:

use JMS\Serializer\Annotation\Type as Type;
class foo {
    /**
     *
     * @Type("array<int,Namespace\To\Class\Bar>")
     * private $bars = array();
     */
 }

JMS Serializer will serialize/deserialize the contents of foo automagically. This use of @Type should be utilized for all attributes of any classes you will be serializing/deserializing.

This also works in situations where you are using string keys (ie. associative array structure). Just substitute "string" for int.

@Type("array<string,Namespace\To\Class\Bar>")
Ultun answered 18/7, 2022 at 18:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.