【问题标题】:Get JSON sub element from NSDictionary从 NSDictionary 获取 JSON 子元素
【发布时间】:2014-02-17 15:50:47
【问题描述】:
我将以下 JSON 格式存储在 NSDictionary 中。我将如何提取audio_link?
{
"results": [
{
"audio_link": "http://www.website.com/Alive.mp3",
"author": "John",
"date_created": "2014-02-17 05:12:25"
}
]
}
我试过了
NSString * songUrl = [[json objectForKey:@"results"] objectForKey:@"url"];
但是失败了。
【问题讨论】:
-
开发者应该知道如何识别 json 中的对象。请有一些时间阅读这里将节省您将来的时间:json.org
标签:
ios
objective-c
json
nsdictionary
【解决方案1】:
你有一个包含字典数组的字典。试试看:
NSString * songUrl = [[json objectForKey:@"results"][0] objectForKey:@"audio_link"];
【解决方案2】:
"results" 是字典数组:
{
"audio_link": "http://www.website.com/Alive.mp3",
"author": "John",
"date_created": "2014-02-17 05:12:25"
}
当您调用 [[json objectForKey:@"results"] objectForKey:@"url"] 时,它会返回包含 key"url" 值字符串的数组
所以,如果你不知道这个数组有多少对象,你最好使用
[[[json objectForKey:@"results"] objectForKey:@"audio_link"] lastObject]
【解决方案3】:
假设您的结果数组中可能有一个、多个或没有项目:
NSArray* results = json [@"result"];
for (NSDictionary* result in results)
{
NSString* audioLink = result [@"audioLink"];
// and so on
}
如果实际上没有任何结果,results [0] 将抛出异常;如果结果中没有项目,即使根本没有结果数组,循环 "for (NSDictionary* result in results) 也能正常工作。
【解决方案4】:
您可以使用Mantle。它以干净的方式解决了这个问题。
例子:
@interface ClassName : MTLModel
@property (nonatomic, strong) NSString *audioLink;
@property (nonatomic, strong) NSString *author;
@property (nonatomic, strong) NSString *creationDate;
@end
@implementation ClassName
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"audioLink" : @"audio_link",
@"author" : @"author",
@"creationDate" : @"date_created"
};
}
@end
ClassName *item = [MTLJSONAdapter modelOfClass:[ClassName class] fromJSONDictionary:jsonDictionary["results"][0] error:nil];