-2

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?

3
  • Does this answer your question? Simple and clean way to convert JSON string to Object in Swift Commented May 28, 2024 at 11:23
  • @tomerpacific : Which answer? By the way b.name = (json["name"] as AnyObject? as? String) ?? "" is not what I wanted to try.. If I have 10 variables in object, I will die... who will manually converts everything... Commented May 28, 2024 at 11:30
  • You can never cast a dictionary to a custom type. Didn’t you get a compiler warning? Commented May 28, 2024 at 12:40

2 Answers 2

0

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)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.