Abhishek Singh Abhishek Singh - 27 days ago 9
JSON Question

Handling 2 keys for same value in single class

I have a use case in which I get score form JSON using

let score = json["score_test"].arrayValue.map {Score.decode(json: $0)}


I have to reuse this class for a response in which only key for the value changes i.e

let score = json["score"].arrayValue.map {Score.decode(json: $0)}


Is there a way to achieve this so that I get the data of Score object whether the key is score_test or score depending on the JSON using the same class?

Also I tried using nil check but since the object is initialized that is not working.

Model of Score:

class Score: Object, Decoder {

dynamic var id: String = ""
dynamic var title: String = ""
dynamic var body: String = ""
dynamic var cardOrder: Int = 0

dynamic var video: Video? = nil

override static func primaryKey() -> String? {
return "id"
}

typealias T = Score

// MARK: Decoder method
static func decode(json: JSON) -> Score {
let id = json["_id"].stringValue
let title = json["title"].stringValue
let body = json["data"].stringValue
let cardOrder = json["card_order"].intValue

var video: Video?
if (json["video"].exists()) {
video = Video.decode(json: json["video"])
}

let score = Score()
score.id = id
score.title = title
score.body = body
score.video = video
score.cardOrder = cardOrder

return score
}
}

Answer Source

From what I understand, score is of type [Score] so what I'd do is:

var score = json["score_test"].arrayValue.map {Score.decode(json: $0)}

if score.isEmpty {
    score = json["score"].arrayValue.map {Score.decode(json: $0)}
}