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.
saveCopyzoom_out_mapuse 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 classMagento\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.
saveCopyzoom_out_map$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.
- How to create JSON controller in Magento 2
- How To Create Magento 2 Module with Admin Grid and Form using UI Component
- How to Create Custom Database in Magento 2
- How to Insert Sample Data in Magento 2
- How to Create Model, Resource Model, and Collection in Magento 2
- How to Add Custom Admin Menu In Magento 2
- How to Create UI Component Grid In Magento 2
- How to Add Mass Action in UI Component Grid in Magento 2
- How to Create UI Component Form and CRUD Operation In Magento 2
- How to Create a Magento 2 Module with Frontend Controller