3

我在 Swift 应用程序中使用 Argo 将 JSON 解码为对象。我有这样的 JSON:

"activities": [
  {
    "id": "intro-to-the-program",
    "type": "session",
    "audio": "intro-to-the-program.mp3"
  },
  {
    "id": "goal-setting",
    "type": "session",
    "audio": "goal-setting.mp3"
  },
  {
    "id": "onboarding-quiz",
    "type": "quiz"
  }
]

基于“类型”,我实际上想实例化 Activity 类的子类(ActivitySession、ActivityQuiz 等)并让子类自己解码。

我怎样才能做到这一点?顶级 decode() 函数需要一个返回类型Decoded<Activity>,到目前为止,我的方法似乎都无法击败它。

4

1 回答 1

2

这是一种方法,您可以通过打开类型以有条件地对其进行解码并在给出无效类型时得到一个很好的错误消息来做到这一点。

struct ThingWithActivities: Decodable {
  let activities: [Activity]

  static func decode(json: JSON) -> Decoded<ThingWithActivities> {
    return curry(ThingWithActivities.init)
      <^> json <|| "activities"
  }
}

class Activity: Decodable {
  let id: String

  init(id: String) {
    self.id = id
  }

  class func decode(json: JSON) -> Decoded<Activity> {
    let decodedType: Decoded<String> = json <| "type"
    return decodedType.flatMap { type in
      switch type {
        case "session": return ActivitySession.decode(json)
        case "quiz": return ActivityQuiz.decode(json)
      default:
        return .Failure(.Custom("Expected valid type, found: \(type)"))
      }
    }
  }
}

class ActivitySession: Activity {
  let audio: String

  init(id: String, audio: String) {
    self.audio = audio
    super.init(id: id)
  }

  override static func decode(json: JSON) -> Decoded<Activity> {
    return curry(ActivitySession.init)
      <^> json <| "id"
      <*> json <| "audio"
  }

}

class ActivityQuiz: Activity {
  override static func decode(json: JSON) -> Decoded<Activity> {
    return curry(ActivityQuiz.init)
      <^> json <| "id"
  }
}

let activities: Decoded<ThingWithActivities>? = JSONFromFile("activities").flatMap(decode)
print(activities) 
// => Optional(Success(ThingWithActivities(activities: [ActivitySession, ActivitySession, ActivityQuiz])))

关键部分是提取类型并.flatMap对其进行 ing 以有条件地解码为应有的类型。

于 2016-07-19T14:53:21.127 回答