【发布时间】:2014-02-04 17:25:26
【问题描述】:
我有一个如下所示的 JSON 响应:
{"load_count":171,"play_count":142,"play_rate":0.9292035398230089,"hours_watched":2.795013611111111,"engagement":0.708595,"visitors":113}
当我尝试将变量设置为此处的值时:
- (id)initWithJSONDictionary:(NSDictionary *)jsonDictionary {
if(self = [self init]) {
// Assign all properties with keyed values from the dictionary
_plays = [jsonDictionary objectForKey:@"load_count"];
_hoursWatched = [jsonDictionary objectForKey:@"hours_watched"];
_engagement = [jsonDictionary objectForKey:@"engagement"];
}
return self;
}
我收到此错误:
2014-02-04 11:16:37.180 BluGiant2[21192:1303] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x10a1176d0
2014-02-04 11:16:37.181 BluGiant2[21192:1303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x10a1176d0'
所以它基本上告诉我它找不到 "load_count" 即使它在那里。由于 JSON 周围没有 [] ,因此它不是对象的问题是什么?
这只是为我加载 JSON 的第二次尝试,另一个有效,我看到的唯一区别是缺少 []。
这就是我所说的:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"https://%s:%s@api.wistia.com/v1/stats/medias/c3e4797d8f.json", "api", "1b75e458de33a9b3f99d33f6bf409a7e145c570a"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSMutableArray *videoDetail = [[NSMutableArray alloc] init];
// Get an array of dictionaries with the key "locations"
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// Iterate through the array of dictionaries
for(NSDictionary *dict in array) {
// Create a new Location object for each one and initialise it with information in the dictionary
VideoDetail *videoD = [[VideoDetail alloc] initWithJSONDictionary:dict];
// Add the Location object to the array
[videoDetail addObject:videoD];
_textPlays.text = [NSNumberFormatter localizedStringFromNumber:videoD.plays numberStyle:NSNumberFormatterNoStyle];
}
}
【问题讨论】:
-
您是在解析字符串还是只是将 JSON 字符串传递给该方法?
-
你怎么称呼
- (id)initWithJSONDictionary:(NSDictionary *)jsonDictionary? -
你必须先解析JSON。
-
使用 JSON 的第 1 条规则是,您不能“烹饪”它或修改您找到的示例。您必须真正研究从特定站点收到的 JSON 格式并了解它的结构,然后相应地编写代码。
标签: ios json nsjsonserialization