Saturday, January 27, 2018

To decode a json string to an object other than stdClass

To decode a json string to an object other than stdClass

$ composer require symfony/serializer
$ composer require symfony/property-access
$ composer require symfony/property-info

<?php
require 'vendor/autoload.php';

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;

$encoders = array(new JsonEncoder());

$normalizers = [
    new ObjectNormalizer(null, null, null, new ReflectionExtractor()),
    new DateTimeNormalizer(),
];

$serializer = new Serializer($normalizers, $encoders);

$person = new Person();
$person->setName('foo');
$person->setAge(99);
$person->setSportsman(false);

$jsonContent = $serializer->serialize($person, 'json');

$person2 = $serializer->deserialize($jsonContent, Person::class, 'json');

echo $jsonContent . PHP_EOL;

echo $person2->getName() . PHP_EOL;

// $jsonContent contains {"name":"foo","age":99,"sportsman":false}
//
// echo $jsonContent; // or return it in a Response

class Person
{
    private $age;
    private $name;
    private $sportsman;

    // Getters
    public function getName()
    {
        return $this->name;
    }

    public function getAge()
    {
        return $this->age;
    }

    // Issers
    public function isSportsman()
    {
        return $this->sportsman;
    }

    // Setters
    public function setName($name)
    {
        $this->name = $name;
    }

    public function setAge($age)
    {
        $this->age = $age;
    }

    public function setSportsman($sportsman)
    {
        $this->sportsman = $sportsman;
    }
}

Reference:

https://stackoverflow.com/questions/5397758/json-decode-to-custom-class

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

No comments: