Lama
Lama

Reputation: 255

loop in nested loop inside json response swift

I have this JSON respone:

{
    "success": false,
    "message": {
       "gender": [
           "The gender field is required."
       ],
       "sms_token": [
           "The sms token field is required."
       ]
   }
}

note that the message object could have more than two elements...

and I'm trying to get the array inside message object... I have tried this:

guard let messages = receivedTodo["message"] as? String, let message = receivedTodo["sms_token"] as? String else {
                    print("Could not get messages from JSON")
                    return
                }
                print("The error is:" + message)
            }

but this didn't work and i will always get "could not get messages from JSON"...

I want to loop and get all of the elements inside message object and print them out.. how to archive this?

Upvotes: 1

Views: 355

Answers (2)

vadian
vadian

Reputation: 285079

Please read the JSON, it's pretty easy, there are only two different collection types, array ([]) and dictionary ({}).

  • The value for key message is a dictionary.
  • The value for key sms_token is an array of String.

    guard let messages = receivedTodo["message"] as? [String:Any], 
          let message = messages["sms_token"] as? [String],
          !message.isEmpty else {
                print("Could not get messages from JSON")
                return
            }
            print("The error is:" + message.joined(separator:", "))
        }
    

    or even

    ...
    guard let messages = receivedTodo["message"] as? [String:[String]],
        let message = messages["sms_token"], !message.isEmpty else { ...
    

To get all error messages – regardless of the dictionary keys – write

guard let messages = receivedTodo["message"] as? [String:[String]] else {
        print("Could not get messages from JSON")
        return
}
for (key, value) in messages {
    print("The \(key) error is: " + value.joined(separator:", "))
}

Upvotes: 2

Salman Ghumsani
Salman Ghumsani

Reputation: 3657

guard let messages = receivedTodo["message"] as? [String:Any],let tokens = messages["sms_token"] as? [String], let genders = messages["gender"] as? [String] else {  
    return
} 
for token in tokens {
      print(token)
}
for gender in genders {
      print(gender)
}

Upvotes: 4

Related Questions