我目前正試圖使用流式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