How to achieve model side-loading with JMS Serializer and Symfony2

佐手、 提交于 2019-12-21 20:54:07

问题


I'm building a project with Ember.js and Ember-data for the UI and Symfony2, FOSRestBundle and JMS Serializer for the backend JSON API. JMS Serializer always embeds nested models in its output, but Ember-data requires that the models are side-loaded. I can't find anywhere an example of configuring JMS Serializer to side-load models rather than embedding them.

Of course, I could just write an adapter on the Ember-data side to transform the result, but I want to gain the benefits of side-loading data and not just work around a (potential) limitation in JMS Serializer.

This is what I mean by embeded model data, which is what JMS-Serializer does now:

{
  "post": {
    "id": 1,
    "name": "Test Post",
    "comments": [
      {
        "id": 1,
        "comment": "Awesome post, man!"
      }, {
        "id": 2,
        "comment": "Yeah, what he said."
      }
    ]
  }
}

This is what I mean by side-loaded model data, which is what I want:

{
  "post": {
    "id": 1,
    "name": "Test Post",
    "comments": [1, 2]
  },
  "comments": [
    {
      "id": 1,
      "comment": "Awesome post, man!"
    }, {
      "id": 2,
      "comment": "Yeah, what he said."
    }
  ]
}

Does anyone know of a configuration to achieve what I want? Or has anyone implemented this functionality in JMS-Serialiser?


回答1:


There is a bundle which supports some more features like async loading and some more flexible implementing and security functions.

https://github.com/UniqueLibs/ember-data-serializer-bundle




回答2:


I've implemented a custom JSON Serialization Visitor class that will side-load the data for embedded objects rather than encode them inline. The class can be found on GitHub here.

Example Usage:

$visitor = new SideLoadJsonSerializationVisitor(
    new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy()));

$serializer = SerializerBuilder::create()
    ->setSerializationVisitor('json', $visitor)
    ->build();

echo $serializer->serialize(array('myClass' => $myClass), 'json');

Or you can use it in your Symfony2 project by overriding the JSON Serialization Visitor class

parameters:
    jms_serializer.json_serialization_visitor.class: 'Acme\MyBundle\Serializer\SideLoadJsonSerializationVisitor'


来源:https://stackoverflow.com/questions/22261499/how-to-achieve-model-side-loading-with-jms-serializer-and-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!