skip to Main Content

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


  1. Chosen as BEST ANSWER

    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)
        }
    }
    

  2. toJSON() function returned a [String: Any] and this cannot be decoded. You may want to try:

    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)))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search