Magento 2 JSON encode or decode

In Magento 2, JSON serialization and unserialization can be performed using the \Magento\Framework\Serialize\Serializer\Json class. This class provides methods to serialize data to JSON format and unserialize JSON-encoded data back to its original PHP representation.

Here's an example of how you can encode or decode JSON data in Magento 2.

use Magento\Framework\Serialize\Serializer\Json; class YourClass { protected $jsonSerializer; public function __construct( Json $jsonSerializer ) { $this->jsonSerializer = $jsonSerializer; } public function serializeData(array $data) { // Serialize data to JSON format $serializedData = $this->jsonSerializer->serialize($data); return $serializedData; } public function unserializeData(string $jsonData) { // Unserialize JSON-encoded data $unserializedData = $this->jsonSerializer->unserialize($jsonData); return $unserializedData; } }

As we know magento 2 deprecated Magento\Framework\Json\Helper\Data class but introduces the new class Magento\Framework\Serialize\Serializer\Json for Json encode or decode.

We've injected new class Magento\Framework\Serialize\Serializer\Json in the above code. You can use the above created methods serializeData and unserializeData for Json encode or decode in Magento 2. Check the below example code for your reference.

$jsonData = '{"key1": "value1", "key2": "value2"}'; // Serialize data $serialized = $youClassInstance->serializeData(['key1' => 'value1', 'key2' => 'value2']); echo "Serialized data: " . $serialized . PHP_EOL; // Unserialize data $unserialized = $youClassInstance->unserializeData($jsonData); echo "Unserialized data: "; print_r($unserialized);

Replace YourClass with the appropriate class where you're implementing serialization and unserialization. The Json class from Magento\Framework\Serialize\Serializer\Json is utilized for this purpose.

Remember to inject the Json serializer in your class constructor via dependency injection to use it within your custom class or block. This way, you can easily serialize and unserialize data using Magento 2's built-in JSON serialization methods.

We hope this article helped you to know How to encode or decode Json data in Magento 2.

Bookmark it for your future reference. Do comment below if you have any other questions or doubts.

P.S. Do share this post with your team.

Review other articles maybe it'll help you too.

Recent Articles
Chrome Extension
Copyright © 2024 All rights reserved.
Ads OFF toggle_off