How to convert raw json to an ember model


#1

In my program I get json from a request that doesn’t go through ember data, but is there a way of converting the json returned into an ember model with all the benefits of ember models?


#2

You can use store.push or store.pushPayload. But you will still need to define a model and possibly even serializer. Any particular reason you’re skirting ember data for the request part?


#3

Hi @amexaCree,

To play with customized json your gonna have to research adapters and serializers. These are Ember-Data components that help you communicate with the backend and massage your json in a uniform way.

Adapters: describes the communication with the backend. Basically, creates the URL string saying what happens when for example post.save() (creates PATCH request) post.createRecord(creates a POST request), etc… happens. You can also specify a host and namespace.

// app/adapters/application.js

export default DS.RESTAdapter.extend({ host: ‘https://backend’, namespace: ‘/api/v2’ });

Serializer: massages the incoming json request. Here you still need to add or delete attributes to conform/normalize the json. There are some examples on the Ember Guides.

It looks like in your scenario, you will need to create a RESTAdapter and JSONSerializer. The first time I used it, it took a while to get used to. But once you do it, it’s easy and you can start using Ember-Data stuff potentially pointing to different backends.

Resources:

https://guides.emberjs.com/v2.18.0/models/customizing-serializers/ https://emberigniter.com/fit-any-backend-into-ember-custom-adapters-serializers/

Best, Elton


#4

I want to return only selected instances of a model to a route, not all of them. Also this model depends on many other models which I also have to process so in the end I feel its easier for me to do it this way.