"表达隐含从字符串强制?'任何" JSON Swift 3

时间:2016-12-01 10:39:06

标签: json swift

您好我有以下要解析的JSON代码

"data":{
            "date":"November 30th, 2016",
            "personality":"Larry",
            "comment":"Saw the homie today"
},

我在viewDidLoad中执行此操作

let url=URL(string:"http://IP-ADDRESS/info.php")

        do {
            let allNotificationsData = try Data(contentsOf: url!)
            let allNotication = try JSONSerialization.jsonObject(with: allNotificationsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
            if let arrJSON = allNotication["notifications"] {
                for index in 0...arrJSON.count-1 {
                    let aObject = arrJSON[index] as? [String: AnyObject]
                    //let name = aObject?["data"]!

                    if let jsonResponse = aObject,
                        let info = jsonResponse["data"] {
                        // Makes sense to check if count > 0 if you're not sure, but...
                        let transaction_id: String? = info["personality"] as? String
                        print(transaction_id)
                        // Do whatever else you need here
                    }

这似乎很好,但控制台返回下面。不确定的时候" nil"但我只是想让它告诉我" date"仅在控制台中的JSON文件中。最终我需要它来捕捉一系列日期,不知道我将如何做到这一点,但我正在研究它。如果你知道我做错了什么,请告诉我。它必须是可选的东西。

1 个答案:

答案 0 :(得分:0)

假设data的父对象是一个数组(您的代码建议),您可以获取数组中的所有data个对象:

   do {
        let allNotificationsData = try Data(contentsOf: url!)
        let allNotification = try JSONSerialization.jsonObject(with: allNotificationsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
        if let arrJSON = allNotification["notifications"] as? [[String:Any]] {
           let infoArray = arrJSON.flatMap { $0["data"] }  
        }

        ...

      }

flatMap的好处是它会忽略nil个值。

如果要访问数组中第一项的comment值,请写

let comment = (infoArray[0] as! [String:Any])["comment"] as! String