我在swift 3中调用api,并从api中获取JSON字符串格式的响应。如何将该JSON字符串转换为Swift中的Dictionary或Array。此外,该JSON字符串包含更多的数组和字典。来自Swift服务器的JSON响应
我试过使用EVReflection工具。它只是转换字典中的上层JSON对象。嵌套字典和数组仍然是字符串格式。
我在swift 3中调用api,并从api中获取JSON字符串格式的响应。如何将该JSON字符串转换为Swift中的Dictionary或Array。此外,该JSON字符串包含更多的数组和字典。来自Swift服务器的JSON响应
我试过使用EVReflection工具。它只是转换字典中的上层JSON对象。嵌套字典和数组仍然是字符串格式。
尝试这样的事情,反响[字符串:任何]所以你必须转换为任何类型的
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
}
}
您会收到jsonData您可以直接尝试JSONSerialization。
如果你收到它作为JSON字符串任何理由,那么你必须是字符串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
我建议你使用SwiftyJson转换。这是一个不可思议的图书馆。 –
还有一篇关于苹果的博客文章:https://developer.apple.com/swift/blog/?id=37 –
看看:http://stackoverflow.com/questions/30480672/how- to-convert-a-json-string-to-a-dictionary – carlito