Magento 2 – Converting JSON to Array of Nested Objects

jsonmagento2mappingobject

I am wanting to understand if there are some functions in Magento Framework which will assist me in mapping an array of nested objects from JSON (such as what would happen when the REST API is building objects from JSON – although in this case I'll be loading from code.)

My structure would be something like this (array of parent_objects)

{"parent_object":[
      {"id":0, "product"{"sku":"prod2", "name":"prod2"},
      {"id":0, "product"{"sku":"prod3", "name":"prod3"}, "customobject":{"field1":"field1-value"}}
 ]
}

And the class I would have the data mapped to is an array of:

\MyNs\Mymodule\Api\Data\ParentObjectDataInterface[] $parentObject

which contains these three properties (mix of primitive and object types)

 @var \Magento\Catalog\Api\Data\ProductInterface $product
 @var int $id
 @var \MyNs\Mymodule\Api\Data\CustomobjectInterface $customobject

Thanks.

EDIT: Currently trying to trace the process:

Appears that in \Magento\Framework\Webapi\Rest\Request\Deserializer\Json we have a method deserialize($encodedBody) that converts JSON to Array.

Then this is used in \Magento\Framework\Webapi\Rest\Request method getBodyParams()

Still tracing my way back now – I've also looked at the reflection classes, don't want to complicate too much and am looking for a solid answer where someone knows the best way.

Best Answer

\Magento\Framework\Json\Helper\Data is deprecated since Magento 100.2.0

You could use \Magento\Framework\Serialize\Serializer\Json instead.

Ie.

 public function __construct(
        \Magento\Framework\Serialize\Serializer\Json $json
    ) {
        $this->json = $json;
    }

 public function yourFunction()
 {
   $jsonDecode = $this->json->unserialize($result);

   $json = $this->json->serialize($jsonDecode);

 }
Related Topic