如何在Decodable中处理多种数据类型?

时间:2019-05-01 03:32:02

标签: swift generics decodable

我已经进行了很多搜索,但是没有任何帮助。我有一个结构:

struct ContestWinnerDetails: Decodable {

var type : Int

var playerStat : WinnerPlayerStat

var stats: [ WinnerDetailStats ]

var filter: WinnerDetailFilter

}

struct WinnerDetailStats: Decodable {

var name: String

var pic: String

var points: String

}

struct WinnerDetailFilter: Decodable {

var start: Int?

var end: Int?

var text: String?

}

struct WinnerPlayerStat: Decodable {

var points: Int

var rank: Int

}

现在,让我们集中讨论WinnerPlayerStat,它包含两个键pointsrank。当前,它们是Int,但是我有一个情况,也可以是String,因此,当String出现时,它就无法解析数据。我该怎么处理IntString

我正在这样解析它:

let decoder = JSONDecoder()

decoder.keyDecodingStrategy = .convertFromSnakeCase

guard let response = try? decoder.decode(ContestWinnerDetails.self, from: response.rawData()) else { return }

self.model = response

0 个答案:

没有答案