Crabar Crabar - 6 months ago 92
JSON Question

Incorrect JSON format for Ember Data

I'm using the latest version of EmberJS and Ember Data.
I have the next JSON data:

[{
"id": 6,
"name": "First object",
"vol": 40,
"description": "bla bla bla",
"category": "first"
}, {
"id": 7,
"name": "Second object",
"vol": 17,
"description": "Some description",
"category": "second"
}]


And the next model:

import DS from 'ember-data';

export default DS.Model.extend({
name: DS.attr('string'),
vol: DS.attr('number'),
description: DS.attr('string'),
category: DS.attr('string')
});


And I don't understand how to make Ember data works. I have suspicious that ember data expects something like next:

[{
model-name {
"id": 6,
"name": "First object",
"vol": 40,
"description": "bla bla bla",
"category": "first"
}
}, {
model-name {
"id": 7,
"name": "Second object",
"vol": 17,
"description": "Some description",
"category": "second"
}
}]


In console I have a bunch of warnings:

WARNING: Encountered "0" in payload, but no model was found for model
name "0" (resolved model name using emdber-drink-
it@serializer:application:.modelNameFromPayloadKey("0"))
WARNING: Encountered "1" in payload, but no model was found for model
name "1" (resolved model name using emdber-drink-
it@serializer:application:.modelNameFromPayloadKey("1"))


And more than hundred similar records (that is how many records server returns on request).
And no data in store.

How can I fix this problem without changing JSON that I receive from server?

Answer

You should be able to add a custom serializer to add a root key to your JSON data. I haven't tested this but you could try something like:

(using a "book" model as an example)

// app/serializers/book.js
import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  extractArray: function(store, type, payload) {
    var newPayload = {};
    newPayload[type.modelName] = payload;
    return this._super(store, type, newPayload);
  }
});

If this is a problem with the entire API, then you might need to make a custom serializer for the entire application and use the passed-in type argument to build the root keys.

Also as a side note, I probably wouldn't use Ember Data if I didn't have control over the API. Unless it follows strict guidelines like jsonapi.org, you're bound to have a few headaches with it.

EDIT - changed answer to the suggestion above (using 'type' to build root key).