NSMutableData到NSDictionary返回null

时间:2015-06-13 04:29:56

标签: ios objective-c nsdictionary nsmutabledata

我正在编写一个使用Instagram API的程序,我遇到了NSMutableData and NSDictionary.

的一些问题

由于我必须多次调用API,因此我决定创建一个NSMutableData object,向它添加较小的NSData对象,然后将整个内容转换为NSDictionary。

但是,当我将NSMutableData appendData NSData,转换为NSMutableData后再次拨打NSDictionary时,字典会返回null。

这是我的一些代码。

NSMutableData *userData = [[NSMutableData alloc]init]
NSData *feed = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString   stringWithFormat:@"https://api.instagram.com/v1/users/17636367/media/recent?access_token=%@",accessToken]]];
[userData appendData:feed];
NSData *moarData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.instagram.com/v1/users/17636367/media/recent?access_token=%@&max_id=%@",accessToken, maxID]]];
[userData appendData:moarData];
NSDictionary *dictTwo = [NSJSONSerialization JSONObjectWithData:userData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dictTwo);

dictTwo返回null。但是,当我只对appendData进行一次调用时,字典不为空。

感谢。

2 个答案:

答案 0 :(得分:2)

当您附加两个单独的JSON响应时,它们将不会形成JSON。

您可以使用以下链接测试最终结果以查看它是否为JSON:

JSON validator

您需要单独解析每个查询响应,然后对该数据应用操作:( Ex NSMutableDictionary,NSMutableArray等)。

答案 1 :(得分:0)

第一个调用将返回一个数组或字典。假设它是一本字典,你会得到类似的东西:

{"some":"data"}

这可以正确解析。当你拨打两个电话时,你会得到:

{"some":"data"}{"other":"data"}

这不是有效的JSON。您需要单独解析每个项目。

相关问题