从Json Response Symfony2中删除代理

时间:2016-04-19 13:56:53

标签: json symfony serialization

我在Symfony2应用程序中工作,我尝试做的是从响应中删除不需要的字段,只显示我想要的字段。

我的JSON看起来像这样:

[
  {
    "id": 1,
    "title": "Granit",
    "typeId": {
      "id": 1,
      "name": "X or Y",
      "acroname": "xory",
      "__initializer__": null,
      "__cloner__": null,
      "__isInitialized__": true
    },
    "pushDate": {
      "timezone": {
        "name": "Europe/Berlin",
        "location": {
          "country_code": "DE",
          "latitude": 52.5,
          "longitude": 13.36666,
          "comments": "most locations"
        }
      },
      "offset": 7200,
      "timestamp": 1460584800
    },
    "addedAt": {
      "timezone": {
        "name": "Europe/Berlin",
        "location": {
          "country_code": "DE",
          "latitude": 52.5,
          "longitude": 13.36666,
          "comments": "most locations"
        }
      },
      "offset": 7200,
      "timestamp": 1460548644
    },
    "deviceToShow": {
      "id": 2,
      "name": "Mobile",
      "__initializer__": null,
      "__cloner__": null,
      "__isInitialized__": true
    },
    "statusSurvey": false,
    "slides": [
      {
        "id": 1,
        "title": "First Question",
        "picture1": "160413015724bazinga2.jpg",
        "picture2": "160413015724th.jpg",
        "idSurvey": 1,
        "absolutePathpic1": "C:\\xampp\\htdocs\\stu-wrapper\\src\\AppBundle\\Entity/../../../web/uploads/slideSurvey/160413015724bazinga2.jpg",
        "webPathpic1": "uploads/slideSurvey/160413015724bazinga2.jpg",
        "absolutePathpic2": "C:\\xampp\\htdocs\\stu-wrapper\\src\\AppBundle\\Entity/../../../web/uploads/slideSurvey/160413015724th.jpg",
        "webPathpic2": "uploads/slideSurvey/160413015724th.jpg",
        "file": null,
        "file1": null
      }
    ],
    "categories": []
  }
]

我想删除" 初始值设定项":null," 克隆者":null,&#34等字段; isInitialized ":true并隐藏时区对象并仅显示" timestamp"。

这是我的控制器,我正在进行序列化和创建Json Response。

public function getAction()
    {
        $em = $this->getDoctrine ()->getManager ();
        $survey = $em->getRepository ( 'AppBundle:Survey' )->findAll ();

        if ( !$survey ) {
            throw $this->createNotFoundException ( 'Data not found.' );
        }
        $encoder = new JsonEncoder();
        $normalizer = new ObjectNormalizer();
        $normalizer->setCircularReferenceHandler ( function ( $survey ) {
            return $survey->getid ();
        } );


        $serializer = new Serializer( array ( $normalizer ), array ( $encoder ) );

        $jsonContent = $serializer->serialize ( $survey, 'json' );

        return new Response( $jsonContent );
    }

谢谢。

2 个答案:

答案 0 :(得分:2)

尝试排除这些字段:

$normalilzer->setIgnoredAttributes(
    [
        "__initializer__", 
        "__cloner__",
        "__isInitialized__"
    ]);

答案 1 :(得分:0)

分离实体以删除对象的doctrine2链接

$em->detach($survey);