我在swift 3中调用了api。从api我得到了JSON字符串格式的响应。如何在Swift中将该JSON字符串转换为字典或数组。此外,JSON字符串还包含其他数组和字典。
我尝试过使用 EVReflection 工具。它只转换字典中的上层JSON对象。嵌套的词典和数组仍然是String格式。
答案 0 :(得分:0)
尝试这样的事情,响应是[String:Any]所以你必须强制转换为任何类型
DispatchQueue.main.async {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
let j = json as NSDictionary
guard let resp = response as? HTTPURLResponse
else {
// No response from server
return
}
if resp.statusCode == 200 {
// You can put here some callback, this is a data you need
} else {
// Here is some error
}
}
} catch {
// And this is a error from server
}
}
答案 1 :(得分:0)
您应该收到jsonData,您可以直接尝试JSONSerialization。
如果由于任何原因你以json String的形式收到它,那么你必须先将该字符串转换为jsonData
// Here you have to convert Json String to jsonData
// if it's not Json String then skip this line
let jsonData = jsonString.data(using: .utf8)
// Try to convert it to json object
do {
let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String : Any]
// now you can try to parse your json
} catch let error as NSError {
print(error.localizedDescription)
}
或者@Jay提到使用Swiftyjson