我正在尝试为ios 6应用程序解析JSON,但似乎无法让它工作。我已经搜索了大量的论坛,但还没有找到一个解决方案,工作,我理解足够的实现,或适用。
如果我错过了一个,我道歉。
首先,我有一个测试WebService,据我所知,返回有效的JSON
http://thetrouthunter.com/SVLocationsAPI.php 第二,这是我的Objective-C代码:+ (NSDictionary *)connectToService:(NSString *)query
{
NSError *error = nil;
query = [NSString stringWithFormat:@"%@&format=json&nojsoncallback=1", query];
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;
NSLog(@"locations: %@", results);
if (error)
NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
return results;
}
+ (NSArray *)userLocation {
NSString *request = [NSString stringWithFormat:@"http://thetrouthunter.com/SVLocationsAPI.php"];
return [[self connectToService:request] valueForKeyPath:@"locations.location"];
}
ls NSLog函数打印错误:"The operation could 't be complete . "(Cocoa错误:3840。)"
我不明白为什么会这样。您正在将%@&format=json&nojsoncallback=1
添加到connectToService:
的URL中,并且新URL的结果是网页,而不是您期望的JSON(即http://thetrouthunter.com/SVLocationsAPI.php&format=json&nojsoncallback=1)。
记录HTTP请求的实际结果可能是有用的,这样你就可以调试它,直到你得到JSON(即在调用序列化函数之前)。