我正在尝试使用NSJSONSerialization来序列化从堆栈溢出API返回的数据,但它没有按预期工作:(
我使用的代码如下:
NSURL *apiURL = [NSURL URLWithString:@"http://api.stackoverflow.com/1.1/questions?tagged=objective-c&pagesize=30"];
NSError *error = nil;
// First option - failed
NSInputStream *inputStream = [NSInputStream inputStreamWithURL:apiURL]; // returning nil
id jsonFound1 = [NSJSONSerialization JSONObjectWithStream:inputStream options:NSJSONReadingMutableContainers error:&error];
// Second option - failed
NSData *jsonData = [NSData dataWithContentsOfURL:apiURL]; // returning correct value, verified after converting it to NSString
id jsonFound2 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; // returning nil
我在Xcode 4.2 for iOS5中尝试上面的代码,我得到(null) inputStream 和 jsonFound2 。
早些时候我是通过SBJSON进行的,它运行正常。
如果我做错了什么或遗失任何东西,有人可以建议我吗?
答案 0 :(得分:3)
我认为在分配inputStream
之后可能会缺少一步。
[inputStream open];
我没有尝试使用远程URL,但看过使用此方法的示例。
答案 1 :(得分:0)
第一个选项不起作用,因为它只支持文件URL(感谢David指点)。
第二个选项适用于远程网址。