Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

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'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top