作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我想解析以下 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”,但我只是希望它仅在控制台中显示 JSON 文件本身中的“日期”。最终我需要它来捕获一系列日期,不知道我将如何做到这一点,但我正在努力。如果您知道我做错了什么,请告诉我。它必须是可选的。
最佳答案
假设 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
关于json - "Expression Implicity Coerced from ' 字符串? ' to Any"JSON swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40908438/
我是一名优秀的程序员,十分优秀!