循环嵌套循环里面的json响应swift

时间:2018-04-11 06:25:49

标签: ios json swift xcode

我有这个JSON响应:

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

请注意,消息对象可能包含两个以上的元素......

我试图将数组放在消息对象中...我试过这个:

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

但是这没有用,我总是得到#34;无法从JSON获得消息" ...

我想循环并获取消息对象中的所有元素并将其打印出来..如何存档?

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

阅读 JSON,这很简单,只有两种不同的集合类型,数组([])和字典({})。

  • message的值是字典。
  • sms_token的值是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:", "))
        }
    

    甚至

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

要获取所有错误消息 - 无论字典键如何 - 写

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:", "))
}