我正在尝试传播NSJSONSerialization的响应:
let responseDict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as NSDictionary
到目前为止,我有一个很好的输出,我想要剖析/传播:
(lldb) po responseDict
{
photos = {
page = 1;
pages = 1333;
perpage = 100;
photo = (
{
farm = 4;
"height_m" = 243;
"height_s" = 117;
"height_sq" = 75;
"height_t" = 49;
id = 15148883617;
isfamily = 0;
isfriend = 0;
ispublic = 1;
owner = "48531100@N04";
secret = fb6596ca90;
server = 3926;
title = "An Exceptional Roman Orichalcum Sestertius of Nero (54-68 C.E.), a Magnificent Depiction of the Temple of Janus on the Reverse";
"url_m" = "https://farm4.staticflickr.com/3926/15148883617_fb6596ca90.jpg";
"url_s" = "https://farm4.staticflickr.com/3926/15148883617_fb6596ca90_m.jpg";
"url_sq" = "https://farm4.staticflickr.com/3926/15148883617_fb6596ca90_s.jpg";
"url_t" = "https://farm4.staticflickr.com/3926/15148883617_fb6596ca90_t.jpg";
"width_m" = 500;
"width_s" = 240;
"width_sq" = 75;
"width_t" = 100;
},
...
...
问题在于传播。 这是“照片”键的内容(与ObjC对应物相比相当丑陋):
(lldb) po responseDict["photos"]
(instance_type = Builtin.RawPointer = 0x00007fce90ec74e0 -> 0x0000000105a910e0 (void *)0x0000000105a91220: __NSDictionaryM)
{
instance_type = 0x00007fce90ec74e0 -> 0x0000000105a910e0 (void *)0x0000000105a91220: __NSDictionaryM
}
此行会导致致命(动态转换)崩溃:
let myPhotos = responseDict["photos"] as NSArray
这是一个ObjC等价物(有效):
jsonDict[@"photos"][@"photo"];
将它与下面给出错误的Swift等价物进行比较(即使我将它转发给NSDictionary):
(lldb) po responseDict["photos"]["photo"]
error: <EXPR>:1:1: error: 'AnyObject?' does not have a member named 'subscript'
responseDict["photos"]["photo"]
问题:如何在Objective-C中尽可能正确地解析Swift中的字典(或任何集合)?
答案 0 :(得分:1)
我设法找到了单独的词典:
let myPhotos = responseDict["photos"] as? NSDictionary
let photos = myPhotos!["photo"] as? NSArray
let myPhoto:AnyObject = photos![0]
println(myPhoto)
这里有输出:
{
farm = 4;
"height_m" = 500;
"height_s" = 240;
"height_sq" = 75;
"height_t" = 100;
id = 15150188169;
isfamily = 0;
isfriend = 0;
ispublic = 1;
owner = "87355413@N02";
secret = e9cfed5225;
server = 3905;
title = "Miss 18mths wearing Music Box pinafore in grey denim (18-24mths). Trimmed with aqua/pink ric rac, and \"bow\" button.";
"url_m" = "https://farm4.staticflickr.com/3905/15150188169_e9cfed5225.jpg";
"url_s" = "https://farm4.staticflickr.com/3905/15150188169_e9cfed5225_m.jpg";
"url_sq" = "https://farm4.staticflickr.com/3905/15150188169_e9cfed5225_s.jpg";
"url_t" = "https://farm4.staticflickr.com/3905/15150188169_e9cfed5225_t.jpg";
"width_m" = 375;
"width_s" = 180;
"width_sq" = 75;
"width_t" = 75;
}
并进一步测试:
let myPhoto = myPhotoInfo["url_m"] as String
产生:
https://farm4.staticflickr.com/3920/15333895891_956d072454.jpg
答案 1 :(得分:0)
根据有效的Objective-C代码,responseDict["photos"]
不是NSArray
,而是NSDictionary
。这应该有效:
let myPhotos = responseDict["photos"] as? NSDictionary
let photo = myPhotos!["photo"]