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?
There is a bundle which supports some more features like async loading and some more flexible implementing and security functions.
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