序列化从后端到存储余烬存储的响应

时间:2015-12-11 09:38:01

标签: json ember.js ember-data ember-cli

我对后端的回复不是ember商店的形式。我无法序列化响应。

response.json

[{
    "pk": 127,
    "url": "http://example.com/api/galleries/127/",
    "gallery_name": "Faces",
    "thumbnail_url": "https://example.cloud.net/galleryThumbs/2656a05c-4ec7-3eea-8c5e-d8019454d443.jpg",
    "time": "1 month ago",
    "description": "Created by user",
    "is_following": true,
    "feedPhotos": [{
            "pk": 624,
            "url": "http://example.com/api/photos/624/",
            "profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
            "userName": "Nabeela",
            "userKarma": 915,
            "caption": "Old woman spinning her 'chhos-khor' ...a rotation of which is equivalent to the recitation of a mantra.",
            "numComments": 0,
            "owner": "http://example.com/api/users/44/",
            "time": "1 month ago",
            "photo_url": "https://example.cloud.net/photos/9cbd6423-3bc5-36e0-b8b4-d725efb3249a.jpg",
            "comments_url": "http://example.com/api/photos/624/comments/",
            "numFives": 4,
            "fivers_url": "http://example.com/api/photogalleries/1362/fivers/",
            "fivers_pk": 1362,
            "fullphoto_url": "http://example.com/api/photogalleries/1362/photo/",
            "fullphoto_pk": 1362,
            "is_fived": true,
            "hiFiveKarma": 1,
            "owner_pk": 44,
            "userFirstName": "Nabeela",
            "is_bookmarked": false
        }, {
            "pk": 574,
            "url": "http://example.com/api/photos/574/",
            "profilePic": "https://example.cloud.net/userDPs/b6f69e4e-980d-3cc3-8b3e-3eb1a7f21350.jpg",
            "userName": "Rohini",
            "userKarma": 194,
            "caption": "Life @ Myanmar!",
            "numComments": 0,
            "owner": "http://example.com/api/users/45/",
            "time": "2 months ago",
            "photo_url": "https://example.cloud.net/photos/eeae72d5-d6af-391e-a218-b442c0c7e34e.jpg",
            "comments_url": "http://example.com/api/photos/574/comments/",
            "numFives": 2,
            "fivers_url": "http://example.com/api/photogalleries/1303/fivers/",
            "fivers_pk": 1303,
            "fullphoto_url": "http://example.com/api/photogalleries/1303/photo/",
            "fullphoto_pk": 1303,
            "is_fived": false,
            "hiFiveKarma": 0,
            "owner_pk": 45,
            "userFirstName": "Rohini",
            "is_bookmarked": false
        }
    ]
}, {
    "pk": 65,
    "url": "http://example.com/api/galleries/65/",
    "gallery_name": "Royal",
    "thumbnail_url": "https://example.cloud.net/galleryThumbs/d8a900af-1f1d-3977-8cc8-b8bb36e32be5.jpg",
    "time": "2 months ago",
    "description": "This is a gallery about Royal",
    "is_following": false,
    "feedPhotos": [{
        "pk": 347,
        "url": "http://example.com/api/photos/347/",
        "profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
        "userName": "Nabeela",
        "userKarma": 915,
        "caption": "I cannot forget the name of this palace - Moti Mahal (translation: Pearl Palace). Indescribably beautiful, ainnit! at Mehrangarh fort, Jodhp",
        "numComments": 0,
        "owner": "http://example.com/api/users/44/",
        "time": "2 months ago",
        "photo_url": "https://example.cloud.net/photos/958ed406-708e-3f01-a2f4-9467cd709fdd.jpg",
        "comments_url": "http://example.com/api/photos/347/comments/",
        "numFives": 4,
        "fivers_url": "http://example.com/api/photogalleries/759/fivers/",
        "fivers_pk": 759,
        "fullphoto_url": "http://example.com/api/photogalleries/759/photo/",
        "fullphoto_pk": 759,
        "is_fived": false,
        "hiFiveKarma": 0,
        "owner_pk": 44,
        "userFirstName": "Nabeela",
        "is_bookmarked": false
    }, {
        "pk": 593,
        "url": "http://example.com/api/photos/593/",
        "profilePic": "https://example.cloud.net/userDPs/95ac6974-f7df-338c-ab84-99fa1df7514c.jpg",
        "userName": "Vikanshu",
        "userKarma": 932,
        "caption": "Marvelous architecture!! in Florence, Italy",
        "numComments": 0,
        "owner": "http://example.com/api/users/48/",
        "time": "1 month ago",
        "photo_url": "https://example.cloud.net/photos/7a86eb37-6c68-3d6c-b6cf-2e3b74d330dd.jpg",
        "comments_url": "http://example.com/api/photos/593/comments/",
        "numFives": 4,
        "fivers_url": "http://example.com/api/photogalleries/1363/fivers/",
        "fivers_pk": 1363,
        "fullphoto_url": "http://example.com/api/photogalleries/1363/photo/",
        "fullphoto_pk": 1363,
        "is_fived": false,
        "hiFiveKarma": 0,
        "owner_pk": 48,
        "userFirstName": "Vikanshu",
        "is_bookmarked": false
    }]
}]

如何使用JSONPISerailizer或ember-cli中的任何其他序列化程序对其进行序列化,以便将其存储在ember存储中

1 个答案:

答案 0 :(得分:2)

Reference jsonapi.org ++++顶级: 根: JSON对象必须是每个JSON API请求响应的根。 文档必须至少包含一个顶级成员: 1.数据:文件“主要数据” 2. errors:一组错误对象(id,status,code,title ....) 3. meta:包含非标准元信息的元对象(版权,作者......)

成员数据和错误不得共存。 “数据”{}

+++++资源对象 1.资源对象必须包含至少一个顶级成员 *ID *型

```
//structure-1
//for galleries
{
  "data": {
    "type": "galleries",
    "id": "1"
  }
}

//for photos
{
  "data": {
    "type": "photos",
    "id": "1"
  }
}
```
  1. 此外,资源对象可以包含任何这些顶级成员 *属性 *关系 *链接 *元
  2. //首先添加属性

    ```
    //structure-2
    //for galleries
    {
      "data": {
        "type": "galleries",
        "id": "1",
        "attributes": {
          "galleryName": "Faces"
          "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
          "description": "Created by user",
        }
      }
    }
    
    //for photos
    {
      "data": {
        "type": "photos",
        "id": "1",
        "attributes":{
           userName: "Nabeela",
           userKarma: 915
         }
      }
    }
    ```
    

    //添加关系 关系对象必须至少包含以下其中一项 *链接(包含“自我”或“相关”资源链接中的至少一个 *数据 *元

    //link in relationship (minimum one required from link,data,meta).
    //
    ```
    //structure-3
    //for galleries
    {
      "data":[{  //Array(square bracket as adding relationship one more item to data
        "type": "galleries",
        "id": "1",
        "attributes": {
          "galleryName": "Faces"
          "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
          "description": "Created by user",
        },
        "relationships":{
           "links":{
          "self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
        },
        }]
      }
    }
    ```
    

    //关系中的数据

    ```
    //structure-4
    //for galleries
    {
      "data": [{
        "type": "galleries",
        "id": "1",
        "attributes": {
          "galleryName": "Faces"
          "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
          "description": "Created by user",
        },
        "relationships":{ //This has all your photo stuff
           "links":{
          "self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
        },
        "data": {       //picked it up from structure-1
              "type": "photos",
              "id": "77"
        }
        }]
      }
    }
    ```
    

    //添加相关资源“included”

    ``` //对于画廊

    {
      "data": [{
        "type": "galleries",
        "id": "1",
        "attributes": {
          "galleryName": "Faces"
          "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
          "description": "Created by user",
        },
        "relationships":{ //This has all your photo stuff
           "links":{
          "self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
        },
        "data": {       //picked it up from structure-1
              "type": "photos",
              "id": "77"
        }
        }],
        "included":[{
            "type": "photos",
            "id": "77",
            "attributes":{
                userName: "Nabeela",
                userKarma: 915
            },
        {
            "type": "photos",
            "id": "78",
            "attributes":{
                userName: "Nabeela",
                userKarma: 915
            }
       }]
    
      }
    }
    

    ```

    对于收藏品。我不自信但是试试这个

    现在收集画廊。

    //用于画廊

    {
      "data": [{
        "type": "galleries",
        "id": "1",
        "attributes": {
          "galleryName": "Faces"
          "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
          "description": "Created by user",
        },
        "relationships":{ //This has all your photo stuff
           "links":{
          "self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
        },
        "data": {       //picked it up from structure-1
              "type": "photos",
              "id": "77"
        }
        },{
        "type": "galleries",
        "id": "2",
        "attributes": {
          "galleryName": "Faces"
          "thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
          "description": "Created by user",
        },
        "relationships":{ //This has all your photo stuff
           "links":{
          "self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
        },
        "data": {       //picked it up from structure-1
              "type": "photos",
              "id": "79"
        }
        }],
        "included":[{
            "type": "photos",
            "id": "77",
            "attributes":{
                userName: "Nabeela",
                userKarma: 915
            },{
            "type": "photos",
            "id": "78",
            "attributes":{
                userName: "Nabeela",
                userKarma: 915
            },{
            "type": "photos",
            "id": "79",
            "attributes":{
                userName: "Nabeela",
                userKarma: 915
            }
       }]
    
      }
    }
    

    ============实施部分=================================

    JSONSerializer规范化过程遵循以下步骤

    * normalizeResponse:输入法。 * normalizeCreateRecordResponse:特定操作的normalizeResponse。 * normalizeSingleResponse | normalizeArrayResponse: - 对于像createRecord这样的方法。我们期待单回记录。 - 对于像findAll这样的方法,我们期待多条记录。

    + normalize = normalizeArray为每个记录迭代并调用normalize normalizeSingle调用它一次。

    + extractID | extractAttributes | extractRelationships =将委托规范化为这些方法,将记录有效负载转换为jsonAPI格式

    从normalizeResponse方法开始。如果你打开并看到normalizeResponse方法

    在json-serializer中 link normalizeResponse:https://github.com/emberjs/data/blob/v2.2.1/packages/ember-

    数据/ LIB /串行器/ JSON-serializer.js#L192

    找到一个切换案例switch(requestType)。如果是requestType if “findRecord”然后调用“normalizeFindRecordResponse” “queryRecord”然后调用“normalizeQueryRecordResponse” “findAll”然后调用“normalizeFindAllResponse” ...等等等等。 如果你注意到传递给所有方法的参数与normalize

    的参数相同

    (...参数):)

    **让我们开始寻找所有 即normalizeResponse - > normalizeFindAllResponse - > normalizeArrayResponse as normalizeFindAllResponse方法只有一行调用

    normalizeArrayResponse。

    normalizeFindAllResponse

    normalizeResponse - > normalizeFindAllResponse - > normalizeArrayResponse - >

    _normalizeResponse {extractMeta,normalize}

    extractMeta [提取元信息,如分页和东西] if single:normalize []

    emberjs docs中规范化方法的示例

    ```
    import DS from 'ember-data';
    
    export default DS.JSONSerializer.extend({
      normalize: function(typeClass, hash) {
        var fields = Ember.get(typeClass, 'fields');
        fields.forEach(function(field) {
          var payloadField = Ember.String.underscore(field);
          if (field === payloadField) { return; }
    
          hash[field] = hash[payloadField];
          delete hash[payloadField];
        });
        return this._super.apply(this, arguments);
      }
    });
    ```
    

    “normalizeArrayResponse调用`return this._normalizeResponse

    (商店,primaryModelClass,有效载荷,ID,请求类型,假)。 所以isSingle是错误的_normalizeResponse方法。所以我们必须推动所有

    包含数组的相关记录 在我们的例子中,照片由下面的片段“_normalizeRespose”

    完成

    方法。 _normalizeResponse

    ```
    else{
      documentHash.data = payload.map((item) => {
        let { data, included } = this.normalize(primaryModelClass,item);
        if(included){
          documentHash.included.push(...included);
        }
        return data;
      });
    
      return documentHash;
    }
    ```
    

    在我们对服务器的JSON响应的背景下,事情仍然不清楚 但至少我们现在知道这个流程。

    让我们尝试将它应用于findAll(根据上面的流程)。

    1. 运行“ember g serializer application”//假设您正在使用ember-cli并且
    2. 打算使这个序列化程序通用于应用程序。

      截至目前,我没有关于如何以及何时调用normalizeResponse的信息。 :( 我只是扫描并猜测从服务器接收商店调用的数据

      normalizeResponseHelpers反过来调用normalizeResponse。

      在任何情况下,“normalizeResponse”都会发送有效载荷和其他必要的

      normalizeFindAllResponse(... arguments)的信息,而这些信息又会调用

      normalizeArrayResponse(... arguments),它们将调用“_normalizeRespone”。

      这是我们需要采取行动的地方 for extraMeta和normalize。 + extraMeta 我不确定你的json响应中是否有任何元信息。 如果有,你可以参考docs中提到的例子

      extractMeta

      所以我猜你可以直接在你的应用程序中使用例子中的normalize方法;)。

      请尝试检查。由于我自己学习余烬,我不能保证它会起作用,但它应该。当我正在学习问题/解决方案时,lonngggg解释是我的想法

      //app/serializers/application.js
      
      +normalize
      ```
      import DS from 'ember-data';
      
      export default DS.JSONSerializer.extend({
        normalize: function(typeClass, hash) {
          var fields = Ember.get(typeClass, 'fields');
          fields.forEach(function(field) {
            var payloadField = Ember.String.underscore(field);
            if (field === payloadField) { return; }
      
            hash[field] = hash[payloadField];
            delete hash[payloadField];
          });
          return this._super.apply(this, arguments);
        }
      });
      ```
      

      服务器JSON中的主键是pk。你也必须提到这个

      http://emberjs.com/api/data/classes/DS.JSONSerializer.html#property_primaryKey 应用程序/串行器/ application.js中

      import DS from 'ember-data';
      
      export default DS.JSONSerializer.extend({
        primaryKey: 'pk'
      });