大佬教程收集整理的这篇文章主要介绍了php – 不要使用Symfony序列化程序显示null元素,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
class Foo { public $apple = 1; public $pear = null; public function serialize() { Utils::serialize($this); } }
我使用以下serialize()调用序列化:
class Utils { public static function serialize($object) { $encoder = new XmlEncoder(); $normalizer = new ObjectNormalizer(); $serializer = new serializer(array($normalizer),array($encoder)); $str = $serializer->serialize($object,'xml') } }
产生的输出给了我:
<apple>1</apple><pear/>
预期的输出应为:
<apple>1</apple>
我查看了Symfony 2.8 doc,并设法通过使用$normalizer-> setIgnoredAttributes(“pear”)找到了一个快速解决方案.
所以改进的序列化静态函数看起来像这样
class Utils { public static function ignoreNullAttributes($object) { $ignored_attributes = array(); foreach($object as $member => $value) { if (is_null($object->$member)) { array_push($ignored_attributes,$member); } } return $ignored_attributes; } public static function serialize($object) { $encoder = new XmlEncoder(); $normalizer = new ObjectNormalizer(); $normalizer->setIgnoredAttributes(Utils::ignoreNullAttributes($object)); $serializer = new serializer(array($normalizer),'xml') } }
然而,这个解决方案并不满足我,因为我有更复杂的情况,其中不同的Foo可以由同一个类拥有.例如
class Bar { public $foo1; // (apple=null; pear=2) public $foo2; // (apple=2; pear=null) public function serialize() { Utils::serialize($this); } }
这里我不能使用setIgnoredAttributes方法,因为$foo1和$foo2没有相同的null元素.此外,我不在这里从子类(即Foo)调用serialize方法,因此setIgnoredAttributes为空.
无需编写复杂的内省代码,如何使用Symfony 2.8序列化器默认隐藏null元素?例如,我已经看到它默认启用了JMSSerializer.
use Symfony\Component\serializer\Normalizer\ObjectNormalizer; use Symfony\Component\serializer\serializer; use Symfony\Component\serializer\Encoder\XmlEncoder; class CustomObjectNormalizer extends ObjectNormalizer { public function normalize($object,$format = null,array $context = []) { $data = parent::normalize($object,$format,$context); return array_filter($data,function ($value) { return null !== $value; }); } } $encoders = array(new XmlEncoder()); $normalizers = array(new CustomObjectNormalizer()); $serializer = new serializer($normalizers,$encoders); // ...
如果我们有一个Person like the one of the official documentation的数组:
// ... $person1 = new Person(); $person1->setName('foo'); $person1->setAge(null); $person1->setSportsman@R_874_5279@; $person2 = new Person(); $person2->setName('bar'); $person2->setAge(33); $person2->setSportsman(null); $persons = array($person1,$person2); $xmlContent = $serializer->serialize($persons,'xml'); echo $xmlContent;
结果将是那些非空节点:
<?xml version="1.0"?> <response> <item key="0"> <name>foo</name> <sportsman>0</sportsman> </item> <item key="1"> <name>bar</name> <age>33</age> </item> </response>
以上是大佬教程为你收集整理的php – 不要使用Symfony序列化程序显示null元素全部内容,希望文章能够帮你解决php – 不要使用Symfony序列化程序显示null元素所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。