我在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"
}
]
基于' type',我实际上想要实例化Activity类的子类(ActivitySession,ActivityQuiz等)并让子类自己解码。
我该怎么做?顶级decode()函数需要返回类型Decoded<Activity>
,到目前为止,我的方法似乎都无法击败它。
答案 0 :(得分: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
覆盖它以有条件地解码为它应该的类型。