2013-08-22 25 views
2

我目前正試圖使用​​流式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]; 
} 
+0

比較http://stackoverflow.com/questions/18362889/error-deserializing-json-stream(以及下面的討論)對於類似的問題。看來NSJSONSerialization無法反序列化多個JSON對象流中的單個JSON對象。 –

+0

你有多個NSURLConnection指向同一個代表嗎?你可能會得到不止一個響應。 –

+0

@JamesRichard這是一個流將連接打開並隨着時間的推移獲得JSON結構,這些結構被附加到NSData中......這是問題的關鍵。我可以'似乎找到一種方法'將所有接收到的json結構合併爲一個'。 – Thomas

回答

1

我想你需要的只是一些額外的邏輯來處理這個實時性。使用你的NSMutableData作爲一個容器來繼續接收數據,但是在每個批次結束時,你應該掃描所有有效對象的數據對象,構建它們,並將它們存儲到一個包含所有構建的json對象的不同對象中。在這個例子讓我們假設你有這樣的伊娃:NSMutableArray的* _wholeObjects

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    // Append the new data to the instance variable you declared 
    NSLog(@"Did Receive data"); 
    [_responseData appendData:data]; 
    [self buildWholeObjects] 
} 

- (void) buildWholeObjects { 
    NSArray *rootObjects = <#business logic to return one whole JSON object per array element, or return nil if none found#> 
    if (rootObjects != nil) { 
    NSUInteger bytesExtracted = 0; 
    for (rootObject in rootObjects) { 
     [_wholeObjects addElement:rootObject]; 
     bytesExtracted += rootObject.length; 
    } 
    NSData *remainingData = [_responseData subdataWithRange:NSMakeRange(bytesExtracted, _responseData.length - bytesExtracted]; 
    [_responseData setData:remainingData]; 
    } 
} 

這樣做只能訪問經過_wholeObjects,其中每個元素代表一個完全有效的JSON對象,你可以反序列化或任何你需要的方式讀取的對象。

只是爲了清楚起見,可以說第一NSData的代表:

{"a":"2"}{"c":"5 

當你處理它_wholeObjects都只有一個單元代表{「一」:「2​​」},並_responseData現在將{ 「C」: 「5

然後數據應繼續在對象上的下一個流可以說第二NSData的是:

"} 

現在_responseData爲{」 C 「:」 5" },因爲我們附加將新消息放到剩餘的舊消息上。我們構建這一個,並在_wholeObjects中獲得第二個元素,_responseData將爲空,並準備好接收下一組數據。

希望有助於一些。我認爲你的難題在於確定有多少_responseData被認爲是有效的JSON對象。如果它們足夠簡單,那麼可以計算打開的數量{/ [關閉} /]並將該子串拉出。

相關問題