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
Answers
Finally I found.. I should have used
JSONDecoder
to decode...Below is what works with me...
toJSON()
function returned a[String: Any]
and this cannot be decoded. You may want to try: