emberjs JSON 格式处理



我的emberjs应用程序中有一个员工模型,我正在尝试使用RESTful Web服务加载员工内容,该服务具有以下格式:

{
    "Result": [
        {
            "EmployeeId": "1",
            "EmployeeName": "Mark Smith",
            "Active": 0,
            "Dept": "Sales"
        },
        {
            "EmployeeId": "2",
            "EmployeeName": "John Smith",
            "Active": 1,
            "Dept": "Sales"
        },
        {
            "EmployeeId": "3",
            "EmployeeName": "Michael Smith",
            "Active": 1,
            "Dept": "Administration"
        }
    ],
    "ResultCount": 3
}

在这里,我面临3个问题:

  1. 是否可以读取这种 JSON 格式并将其添加到员工模型中,我知道"结果"应该是"员工",但我无法控制返回的 JSON 格式,所以如果可以使用"结果"那就太好了。任何这样做的例子都受到高度赞赏。

  2. 如何处理"结果计数"?有没有办法将其作为员工模型的一部分来阅读?

  3. 如何在应用程序视图中将"活动"读作"活动"/"非活动"而不是 0 或 1?

感谢您抽出宝贵时间

正如jasonpgignac所指出的,你需要编写一个自定义的serailizer/deserializer来将数据放入ember-data中。

加载数据后,不需要 ResultCount。应在返回的集合上使用"length"属性。

作为序列化程序的一部分,您需要在模型中将 0/1 转换为假/真。您可以添加如下属性:

activeLabel: ( ->
  if @get('active')
    'Active'
  else
    'Not Active'
).property('active')

并在模板中使用此属性。

根据要求,这是我的一个项目的示例类:

App.StudentSerializer = DS.ActiveModelSerializer.extend
  serializeBelongsTo: (record, json, relationship) ->
    key = relationship.key
    if key is 'attendance'
      @serializeAttendance(record, json)
    else
      json["#{key}_id"] = record.get("#{key}.id")
  serializeAttendance: (record, json) ->
    attendance = record.get('attendance')
    json['attendance'] = {}
    ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'].forEach( (day) =>
      json['attendance'][day] = attendance.get(day)
    )
  serializeHasMany: (record, json, relationship) ->
    key = relationship.key
    jsonKey = Ember.String.singularize(key) + '_ids'
    json[jsonKey] = []
    record.get(key).forEach( (item) ->
      json[jsonKey].push(item.get('id'))
    )

我的商店咖啡看起来像:

App.Store = DS.Store.extend
  # Override the default adapter with the `DS.ActiveModelAdapter` which
  # is built to work nicely with the ActiveModel::Serializers gem.
  adapter: '_ams'
App.ApplicationSerializer = DS.ActiveModelSerializer.extend()

您可能希望使用 JsonAdapter 并扩展它,如果您无法控制后端。正如我在下面所说,我还没有完成反序列化,但应该有必要的钩子供您转换为 ember-data 所需的格式。

最新更新