【发布时间】:2019-10-31 21:14:12
【问题描述】:
我有一个自定义 Symfony 4 反序列化器
class CardImageDecoder implements EncoderInterface, DecoderInterface
{
public function encode($data, $format, array $context = [])
{
if($format !== 'json') {
throw new EncodingFormatNotSupportedException(sprintf('Format %s is not supported by encoder %s', $format, __CLASS__));
}
$result = json_encode($data);
if(json_last_error() !== JSON_ERROR_NONE) {
// don't bother with a custom error message
throw new \Exception(sprintf('Unable to encode data, got error message: %s', json_last_error_msg()));
}
return $result;
}
public function supportsEncoding($format)
{
return 'json' === $format;
}
public function decode($data, $format, array $context = [])
{
if($format !== 'array') {
throw new DecodingFormatNotSupportedException(sprintf('Format %s is not supported by encoder %s', $format, __CLASS__));
}
if(!is_array($data)) {
throw new \UnexpectedValueException(sprintf('Expected array got %s', gettype($data)));
}
$cardInstance = new CardImages();
$cardInstance->setHeight($data['h'] ?? 0);
$cardInstance->setPath($data['url'] ?? '');
$cardInstance->setWidth($data['w'] ?? 0);
return $cardInstance;
}
public function supportsDecoding($format)
{
return 'array' === $format;
}
}
我反序列化的方式非常简单:
$json = '
{
"url": "some url",
"h": 1004,
"w": 768
}';
$encoders = [new CardImageDecoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
$cardImage = $serializer->deserialize(json_decode($json, true), CardImages::class, 'array');
/** @var $cardImage CardImages */
var_dump($cardImage);
但是,我得到了这个结果:
object(App\Entity\CardImages)#158 (5) {
["id":"App\Entity\CardImages":private]=>
NULL
["path":"App\Entity\CardImages":private]=>
NULL
["height":"App\Entity\CardImages":private]=>
NULL
["width":"App\Entity\CardImages":private]=>
NULL
["movie":"App\Entity\CardImages":private]=>
NULL
}
现在,如果我要进行转储,就在解码器的 decode 部分返回之前,我会得到这个:
...
$cardInstance->setWidth($data['w'] ?? 0);
var_dump($cardInstance);
object(App\Entity\CardImages)#153 (5) {
["id":"App\Entity\CardImages":private]=>
NULL
["path":"App\Entity\CardImages":private]=>
string(8) "some url"
["height":"App\Entity\CardImages":private]=>
int(1004)
["width":"App\Entity\CardImages":private]=>
int(768)
["movie":"App\Entity\CardImages":private]=>
NULL
}
忽略未设置的属性(我觉得很好),它应该可以很好地工作,但事实并非如此。
对于我的一生,我无法弄清楚出了什么问题。
感谢任何帮助。
【问题讨论】:
-
我对序列化程序组件没有太多经验,但不是 encoder 旨在将 array 编码为格式(例如 json ) 和反向解码?但是,您返回一个对象,我觉得这很奇怪。它可能应该是一个数组。规范化器(或准确地说是反规范化器)会将某些东西变成一个对象。您是否尝试过返回数组?据我所知,你想要一个非规范化器,但要实现一个解码器......参见图形:symfony.com/doc/current/components/serializer.html
-
为什么不使用
denormalizer将数组/json 转换为对象?