I have json response as below.
{"StatusCode":1,"Data":{"AndroidVersion":"1","IOSVersion":"1"},"Pager":null,"Error":null}
Now I want to convert to model where I have string extension as below.
func toJSON() -> Any? {
guard let data = self.data(using: .utf8, allowLossyConversion: false) else { return nil }
return try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
}
Model is as below
struct MobileSettingsModel : Codable {
var StatusCode : Int?
}
Now I try to use as below.
let settingObject : MobileSettingsModel = response.toJSON() as? MobileSettingsModel ?? MobileSettingsModel()
"settingObject==(settingObject)".printLog()
Why I get response as below
settingObject==MobileSettingsModel(StatusCode: nil)
I was expecting it to be
settingObject==MobileSettingsModel(StatusCode: 1)
Any idea what I am missing?
2
Finally I found.. I should have used JSONDecoder
to decode…
Below is what works with me…
if let data = response.decryptMessage().data(using: .utf8) {
do {
let yourModel = try JSONDecoder().decode(MobileSettingsModel.self, from: data)
print("JSON Object:", yourModel)
} catch {
print("Error parsing JSON:", error)
}
}
toJSON()
function returned a [String: Any]
and this cannot be decoded. You might want to try this:
func convert<T: Codable>() -> T? {
guard let data = self.data(using: .utf8, allowLossyConversion: false) else { return nil }
return try? JSONDecoder().decode(T.self, from: data)
}
let settingObject: MobileSettingsModel? = response.convert()
//Optional(MyAnswer.MobileSettingsModel(StatusCode: Optional(1)))