将数据序列化/规范化为JSON:如何以编程方式更改输出映射


Serialization / Normalizing of data to JSON: How to programmatically change the output mapping?

我有以下控制器/操作:

 public function messagesAction()
  {
    $encoders = array(new JsonEncoder());
    $normalizers = array(new GetSetMethodNormalizer());
    $serializer = new Serializer($normalizers, $encoders);
    $message = $this->getDoctrine()
      ->getRepository('AcmeStoreBundle:Message')
      ->findAll();
    $response = new Response($serializer->serialize($message, 'json')); 
    $response->headers->set('Content-Type', 'application/json');
    return $response;
  }
}

它发送以下json:

[
    {
        "id": 1,
        "iam": 1,
        "youare": 2,
        "lat": 50.8275853,
        "lng": 4.3809764,
        "msgbody": "Lorem ipsum lorem ipsum lorem ipsum"
    },
    {
        "id": 2,
        "iam": 1,
        "youare": 2,
        "lat": 50.8307348,
        "lng": 4.3734823,
        "msgbody": "What up?"
    }
]

我没有命名密钥,这使得我的Javascript fw(Ember)很难获得一些对象。

我想将Json输出更改为:

[
    {
      "message": {
        "id": "1",
        "iam": "male",
        "youare": "female",
        "lat": "50.8307348"
      }
    }
]

我知道有些正则表达式我可以玩,但我真的不知道在哪里。正如您所看到的,我使用的是标准的开箱即用的序列化程序(这是我返回有效Json的唯一方法)。它有做我想做的事的选项吗?(额外的好处:在发送数据之前,我还需要对数据进行处理。)

为了解决这类问题,我开发了一个sf2捆绑包,可以将数据导出为不同的格式,您可以使用树枝模板自定义输出

https://github.com/IDCI-Consulting/ExporterBundle

希望这会有用。