【问题标题】:How deserialize array in SymfonySymfony中如何反序列化数组
【发布时间】:2016-02-19 09:53:57
【问题描述】:

我想在 Symfony 中将数组反序列化为类,但如果不使用 json 或 XML,我找不到方法。

这是类:

class Product
{
    protected $id;
    protected $name;
    ...
    public function getName(){
    return $this->name;
    }
    ...

} 

我想反序列化为 Product 类的数组。

$product['id'] = 1;
$product['name'] = "Test";
...

【问题讨论】:

标签: php arrays json symfony deserialization


【解决方案1】:

您需要直接使用反规范化器。

版本:

class Version
{
    /**
     * Version string.
     *
     * @var string
     */
    protected $version = '0.1.0';

    public function setVersion($version)
    {
        $this->version = $version;

        return $this;
    }
}

用法:

use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Version;

$serializer = new Serializer(array(new ObjectNormalizer()));
$obj2 = $serializer->denormalize(
    array('version' => '3.0'),
    'Version',
    null
);

dump($obj2);die;

结果:

Version {#795 ▼
  #version: "3.0"
}

【讨论】:

    【解决方案2】:

    你可以通过这样的反思来做到这一点..

    function unserialzeArray($className, array $data)
    {
        $reflectionClass = new \ReflectionClass($className);
        $object = $reflectionClass->newInstanceWithoutConstructor();
    
        foreach ($data as $property => $value) {
            if (!$reflectionClass->hasProperty($property)) {
                throw new \Exception(sprintf(
                    'Class "%s" does not have property "%s"',
                    $className,
                    $property
                ));
            }
    
            $reflectionProperty = $reflectionClass->getProperty($property);
            $reflectionProperty->setAccessible(true);
            $reflectionProperty->setValue($object, $value);
        }
    
        return $object;
    }
    

    然后你会这样称呼..

    $product = unserializeArray(Product::class, array('id' => 1, 'name' => 'Test'));
    

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 2018-04-26
      • 1970-01-01
      • 2014-05-27
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      相关资源
      最近更新 更多