使用JSMSerializerBundle反序列化多维JSON API响应

时间:2015-01-13 11:47:48

标签: json symfony json-deserialization jmsserializerbundle jms-serializer

我使用Symfony2 / JSMSerializerBundle。

将平面json对象序列化为PHP对象非常有用。但是我使用的API提供了一个多维的Json响应:

{
"Webmessage": {
    "@version": "1.0",
    "Header": {
        "Country": "NL",
        "Language": "NL"
    },
    "Content": {
        "Filters": {
            "Sizes": {
                "Size": [
                    {
                        "@id": "241",
                        "#text": "3,5"
                    },
                    {
                        "@id": "55",
                        "#text": "36"
                    }
                ]
            },
            "Colours": {
                "Colour": [
                    {
                        "@id": "159",
                        "#text": "wit"
                    },
                    {
                        "@id": "54",
                        "#text": "zwart"
                    }
                ]
            }
        }
    }
}

}

作为反序列化的PHP我想要这样的东西:

Array
(
[sizes] => Array
    (
      [0] => AppBundle\Entity\Filter Object
      (
        [id:AppBundle\Entity\Filter:private] => 1
        [text:AppBundle\Entity\Filter:private] => Heren
       )

      [1] => AppBundle\Entity\Filter Object
      (
        [id:AppBundle\Entity\Filter:private] => 2
        [text:AppBundle\Entity\Filter:private] => Dames
      )
    )

[colour] => Array
    (
      [0] => AppBundle\Entity\Filter Object
      (
        [id:AppBundle\Entity\Filter:private] =>56
        [text:AppBundle\Entity\Filter:private] => Black
       )

      [1] => AppBundle\Entity\Filter Object
      (
        [id:AppBundle\Entity\Filter:private] => 212
        [text:AppBundle\Entity\Filter:private] => Yellow
      )
    )

谁有提示我怎么做?

谢谢!

1 个答案:

答案 0 :(得分:1)

也许您可以先解码它,然后使用Normalizer创建实体。像这样:

document.location.href

请注意,我没试过这个。我不知道规范化器是否会以这种方式工作,但我知道它用于在数组和Symfony实体之间进行规范化和非规范化。

有关进一步调查,您可以查看Serializer文档: http://symfony.com/doc/current/components/serializer.html

或Normalizer: http://api.symfony.com/2.3/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.html

这里有关于json_encode的一些事情: http://php.net/manual/en/function.json-decode.php