Magento – how to properly serialize / unserialize magento 2 models to json format

jsonmagento2serializerunserialize

I'm trying to retrieve some data from a controller in a serialized format that I can unserialize later. For example, I have created an entity with the following data fields

MyEntity

  • entity_id
  • identifier
  • created_at
  • updated_at

In my controller's execution method I retrieve the list of results based on my criteria.

Now I would like to return a JSON response serialized object in this format

{result:[{'entity_id': 'id', 'identifier': 'identifier'},{...},{...}]}`

I'm trying to use the SerializerInterface to do this

serializer->serialize($item)

but serializing the entities gives empty values like this which is my first issue.

{"result":[{},{},{},{}]}

Later on, in another controller, I would have loved to do the following based on the results retrieved from the first controller which is my second issue.

unserialize($response->getBody()->getContents()->result)

And give me an array of MyEntity items

MyEntity[]

In Symfony, I can already do this using the serializer component which is very powerful and allows me to group attributes I want to expose and also ignore things I don't want to expose so I guess I'm looking for something similar. Is there a Magento 2 implementation for this?

https://symfony.com/doc/current/components/serializer.html

After further digging I noticed that the serializer for json executes a simple json_encode so there probably isn't any standard implementation for serializing/unserializing an object. The best I could do to serialize the Model was to implement in my model the \JsonSerializable interface like this

 public function jsonSerialize()
    {
        return [
          self::KEY_KEY => $this->getData(self::KEY_KEY),
          self::KEY_IDENTIFIER => $this->getData(self::KEY_IDENTIFIER),
          self::KEY_NAME => $this->getData(self::KEY_NAME),
          self::KEY_DESCRIPTION => $this->getData(self::KEY_DESCRIPTION),
        ];
    }

I would love to be able to utilize a framework method to do this though so I'm still looking for an answer to this as well as to how to decode the serialized string back to the Object's Class.

Best Answer

I highly suggest using \Magento\Framework\Serialize\Serializer\Json