我试图解析一个json字符串:
if let jsonStr = asd.value(forKey: "orderData") as? String {
print(jsonStr)
let data = jsonStr.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject] // CRASHES HERE
if let names = json["product_name"] as? [String] {
print(names)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
但在let json = try JSONSeri...
行,它崩溃说Could not cast value of type '__NSArrayI' to 'NSDictionary'.
还尝试将此as! [String: AnyObject]
更改为as! [[String: AnyObject]]
。但它仍然无法发挥作用。
这是我的json字符串结构:
[
{
"product_id" : "1",
"category_json" : {
"category_id" : "1",
"category_name" : "nvm"
},
"selling_price" : "200",
"product_name" : "nvm",
},
{
"product_id" : "2",
"category_json" : {
"category_id" : "2",
"category_name" : "cas"
},
"selling_price" : "800",
"product_name" : "cas",
}
]
答案 0 :(得分:2)
你不应该强迫施放!除非你100%确定它会成功。
我建议您使用以下内容:
let jsonArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]]
这将返回一个产品列表。如果您需要一个产品名称列表,而不是迭代它并提取每个项目的产品名称。你可以这样做:
let names = jsonArray.map({ $0["product_name"] as? String })
答案 1 :(得分:2)
如前所述,对象是一个数组,你必须使用for循环来获取所有项
...
let data = Data(jsonStr.utf8)
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
for item in json {
if let name = item["product_name"] as? String {
print(name)
}
}
}
} catch {
print("Failed to load: \(error.localizedDescription)")
}