I define a model like this:
struct DMTest: Codable {
var uid: Int
var name: String?
}
and do the model decode like this:
let jsonStr = "{\"uid\":123,\"name\":\"haha\"}"
let jsonData = jsonStr.data(using: .utf8)!
do {
let decoder = JSONDecoder()
let result = try decoder.decode(DMTest.self, from:jsonData)
XCGLogger.debug("result = \(result)")
}catch {
XCGLogger.debug("error")
}
When jsonStr is like below, it works well:
{"uid":123,"name":"haha"}
when jsonStr is like below, it will throw a exception:
{"uid":"123","name":"haha"}
It means that if the type of the "uid" not adapter, it can't be decode. But some times the framework of server is weak type, it may give me dirty data like this, How can I adjust the type?
For example: I define Int in the model, if the server give some data of String type and I can covert it to Int, just decode to Int otherwise throw ecxeption.