I had issue with JSON parsing in Swift 4.2. Here is the following code which shown runtime error.
My Json data is as follow which i got from server.
{
code: 406,
message: "Email Address already Exist.",
status: 0
}
I am using Codable to create my structure as follow
struct Registration: Codable {
var code: Int
var status: Int
private enum CodinggKeys: String, CodingKey {
case code
case status
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
do {
self.code = Int(try container.decode(String.self, forKey: .code))!
} catch DecodingError.typeMismatch {
let value = try container.decode(Double.self, forKey: .code)
self.code = Int(value);
}
do {
self.status = try container.decode(Int.self, forKey: .status)
} catch DecodingError.typeMismatch {
let value = try container.decode(String.self, forKey: .status)
self.status = Int(value);
}
}
}
But every time i got error on parsing status key.
Note: I had tried to parse status in String, Int, Double, Decimal, NSInterger but neither any works. every time i got the same error. Expected to decode UInt but found a number instead.
CodingKey
enum.CodinggKeys
instead ofCodingKeys
. could this be the problem? maybe it is taking another enum from your project instead of the one you just declared – Methadoneinit(from:)
here.Codable
can handle it automatically. – Terrill