I am traversing some JSON Data where I need to access nested elements. Currently the easiest way is manually traverse the JSON Data as dictionaries like so
typealias JSON = AnyObject
typealias JSONDictionary = Dictionary<String, JSON>
typealias JSONArray = Array<JSON>
if let jsonData = data["preview"] as? JSONDictionary {
if let source: JSON = jsonData["images"] as? JSONArray {
if let images = source[0] as? JSONDictionary {
if let image = images["source"] as? JSONDictionary {
if let url = image["url"] as? String {
self.imageURL = url
getPhoto()
}
}
}
}
}
This seems unsustainable and the code is ugly. Is there a better way to do this? How can I better traverse JSON data?
答案 0 :(得分:4)
Try this using multiple levels seperated by commas:
if let
jsonData = data["preview"] as? JSONDictionary,
source = jsonData["images"] as? JSONArray,
images = source[0] as? JSONDictionary,
image = images["source"] as? JSONDictionary,
url = image["url"] as? String
{
self.imageURL = url
getPhoto()
}