问题
I am using ember data to get data from a remote server. My model definition is as follows -
App.Publisher = DS.Model.extend({
name: DS.attr('string'),
appName: DS.attr('string'),
url: DS.attr('string'),
appType: DS.attr('number'),
streamType: DS.attr('number'),
sslEnabled: DS.attr('number'),
protocol: DS.attr('number'),
});
And the response from the server is in the following format -
{
id: 1,
name: "aurus",
url: "1111",
app_name: "superprofs",
app_type: 1,
stream_type: 1,
ssl_enabled: 1,
protocol: 1,
created_at: "2014-08-08T10:52:40.000Z",
updated_at: "0000-00-00 00:00:00"
},
But since the key from server
is in underscore
format and my model
keys are camelCase
,
the values from the server are not being set.
How can I make my model keys to adapt to the format of data the server is sending(underscore
) and then when I call save/create/update in ember js, I want the data to be sent in underscore
format, since my server API is expecting the data in the underscore format
回答1:
For the folks who are running into the same problem, I fixed it using ActiveModelAdapter
I made my ApplicationAdpater to extend from DS.ActiveModelAdapter.
App.ApplicationAdapter = DS.ActiveModelAdapter.extend({});
回答2:
You would need to create App.PublisherSerializer
which depending on which adapter you are using should extend from either the DS.RESTSerializer
, DS.ActiveModelSerializer
or DS.JSONSerializer
.
You would need to overwrite the serialize and normalizePayload hooks to do what you need.
keep in mind that ember data needs to have a root key with of the record type, in the normalizePayload hook you should end up returning an object looking like
{
publishers: [{
id: 1,
name: "aurus",
url: "1111",
appName: "superprofs",
appType: 1,
streamType: 1,
sslEnabled: 1,
protocol: 1,
createdAt: "2014-08-08T10:52:40.000Z",
updatedAt: "0000-00-00 00:00:00"
}]
}
here is a bin showing how to use the normalizePayload
hook: http://emberjs.jsbin.com/mucici/1/edit
来源:https://stackoverflow.com/questions/25203749/ember-data-serialize-on-fetch-and-deserialize-on-post