11

I want to deserialize something like this:

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

Any idea how to do this?

mykiwi
  • 1,671
  • 1
  • 19
  • 35
  • You may start from the documentation: http://jmsyst.com/libs/serializer/master/usage – zerkms Jun 11 '17 at 08:56
  • 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")` but it does not work since the array should have a key to work – mykiwi Jun 11 '17 at 08:58
  • So if it doesn't belong to an entity, its just json - so what is wrong with using php's json_decode? – Jenne Jun 11 '17 at 09:04
  • 1
    The goal of using jms/serializer is to transforme json string into your objects, not stdClass like when using json_decode – mykiwi Jun 11 '17 at 09:05
  • `$serializer->deserialize($json, 'array', 'json');` ? Where `T` is the type with `id` property. – zerkms Jun 11 '17 at 09:38
  • Almost, but thanks ! It work with `deserialize($json, "array")` you can post the answer if you want. – mykiwi Jun 11 '17 at 09:44

2 Answers2

34

It would be

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

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

Christian
  • 27,509
  • 17
  • 111
  • 155
zerkms
  • 249,484
  • 69
  • 436
  • 539
  • 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) – ka_lin Sep 09 '20 at 11:36
  • 1
    Figured it out: `$this->serializer->deserialize($result, 'array>', 'json')` – ka_lin Sep 09 '20 at 12:19
0

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>")
gview
  • 14,876
  • 3
  • 46
  • 51