我有一个json字符串转换为字符串数组,如下所示:
let str = "{ \"dtResult\": [ { \"itmdtl_item_no\": \"AO406705959SE3\" }, { \"itmdtl_item_no\": \"AO406708959SE3\" } ] }"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
let result = json["dtResult"] as? [[String:Any]] ?? [ ]
let item = result[0] as! [String:Any]
print(item)
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
当我打印出项目的结果时,我得到了这样的值:
[“itmdtl_item_no”:AO406705959SE3]
但我只想要字符串“AO406705959SE3”,我该怎么办?感谢。
答案 0 :(得分:0)
首先不要写
let result = json["dtResult"] as? [[String:Any]] ?? [ ]
如果result
为nil
或为空,则应用会在result[0]
上崩溃
而是写入以检查数组是否存在且不为空
if let result = json["dtResult"] as? [[String:Any]], !result.isEmpty {
let item = result[0] as! [String:Any]
// Now get the value for key "itmdtl_item_no"
if let itemNo = item["itmdtl_item_no"] as? String {
print(itemNo)
}
}