gpt4 book ai didi

json - "Expression Implicity Coerced from ' 字符串? ' to Any"JSON swift 3

转载 作者:行者123 更新时间:2023-11-30 12:51:22 25 4
gpt4 key购买 nike

您好,我想解析以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com