我目前正试图使用流式API从Twitter中传输数据。我附上下面的代码来创建我的NSData
并附加到didReceiveData
。出于某种原因,每次didReceiveData
都会从Twitter获得响应,它会作为新的JSON根添加到NSData
中,所以当我试图将NSData
解析为JSON结构时,它就会崩溃。Objective-C NSURLConnection didReceiveData在NSData中创建错误的JSON
我无法弄清楚发生了什么,并将JSON发布到验证器中,并注意到JSON中有多个根。我如何修改代码以继续附加到现有的JSON根目录?或者当NSData
中有多个JSON条目时,是否有更简单的方法可以将反序列化转换为JSON?
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
NSLog(@"Did receive response");
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
NSLog(@"Did Receive data");
[_responseData appendData:data];
}
比较http://stackoverflow.com/questions/18362889/error-deserializing-json-stream(以及下面的讨论)对于类似的问题。看来NSJSONSerialization无法反序列化多个JSON对象流中的单个JSON对象。 –
你有多个NSURLConnection指向同一个代表吗?你可能会得到不止一个响应。 –
@JamesRichard这是一个流将连接打开并随着时间的推移获得JSON结构,这些结构被附加到NSData中......这是问题的关键。我可以'似乎找到一种方法'将所有接收到的json结构合并为一个'。 – Thomas