Dewan Payroda Dewan Payroda - 2 days ago 5
Swift Question

"Expression Implicity Coerced from 'String?' to Any" JSON Swift 3

Hi I have the below JSON code I would like to parse

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


I'm doing this in my 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
}


Which seems to be fine but console returns below. Not sure while "nil" but I just want it show me "date" in the JSON file itself only in the console. Eventually I'll need it to catch an array of dates, not sure how I'll do that but I'm working on it. Let me know if you know what I'm doing wrong. It has to be something with optional.

Answer

Assuming the parent object of data is an array (your code suggests that) you can get all data objects in an array with:

   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"] }  
        }

        ...

      }

The benefit of flatMap is it ignores nil values.

If you want to access the comment value of the first item in the array write

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