将 JSON 解码为 Symfony 实体
有谁知道除了编写自定义脚本将 JSON 对象解码为 PHP 实体之外是否有一种简单的方法?
我使用下面的脚本编码为 JSON,但是当我解码时它是一个数组而不是一个实体。
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($coupon, 'json');
$session->set('json', $json);
然后我以这种方式解码
$session = $this->getRequest()->getSession();
$json = $session->get('json');
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
$coupon = $serializer->decode($json, 'json');
但就像我说的......它不再是一个优惠券实体,它只是一个数组。
Does anyone know if there is an easy way, aside from writing a custom script to decode a JSON object into a PHP entity?
I'm using the script below to encode to JSON, but when I decode it's an array and not an entity.
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$json = $serializer->serialize($coupon, 'json');
$session->set('json', $json);
Then I'm decoding in this manner
$session = $this->getRequest()->getSession();
$json = $session->get('json');
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
$coupon = $serializer->decode($json, 'json');
But like I said... it's no longer a Coupon entity, it's just an array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设以下工作正常:
$coupon
是序列化数据的标准化数组。然后假设您希望实例化此数据的类名为Coupon
,您需要对其进行非规范化:注意命名空间,类名
Coupon
可能不正确。Assuming the following works:
$coupon
is a normalized array of the serialized data. Then assuming the class you want this data to be instantiated of is calledCoupon
, you need to denormalize it:Mind the namespaces, the classname
Coupon
might not be correct.我建议使用 JMSSerializerBundle。
它的序列化器比序列化器组件中的序列化器先进得多。
I would recommend using the JMSSerializerBundle.
Its serializer is way more advanced than the serializer that the one from the Serializer Component.
另一个有趣的选择 JSON 类提示。
Another interesting option with JSON class hinting.