2012-08-13 33 views
4

我無法搞清楚這個錯誤了:JSON錯誤的iOS:在JSON無效的頂級類型寫

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization writeJSONObject:toStream:options:error:]: Invalid top-level type in JSON write' 

其中涉及到這個塊的代碼(基本上我創建一些JSON和發送它關閉到服務器)。我已經檢查過服務器,看看這個套接字是否被打開,它是哪個!

NSDictionary *blobData = [NSDictionary dictionaryWithObjectsAndKeys: 
          sendString,@"string", 
          nil]; 
NSString *blobString = [[NSString alloc] 
         initWithData:[NSJSONSerialization dataWithJSONObject:blobData options:kNilOptions error:&error] 
         encoding:NSUTF8StringEncoding]; 
NSLog(@"Blob Created: %@", blobString); 
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys: 
          @"send_string",@"request_type", 
          [NSNumber numberWithInt:0],@"security_level", 
          @"ios",@"device_type", 
          //No Email Provided, This is just for testing 
          blobData,@"blob", 
          nil]; 

NSData *JSONRequestData = NULL; 
if ([NSJSONSerialization isValidJSONObject:requestData]) { 
    NSLog(@"Proper JSON Object"); 
    JSONRequestData = [NSJSONSerialization dataWithJSONObject:requestData options:kNilOptions error:&error]; 
} 
else { 
    NSLog(@"requestData was not a proper JSON object"); 
    return FALSE; 
} 
NSLog(@"Error:%@",[[error userInfo] objectForKey:@"NSDebugDescription"]); 
NSLog(@"Contents of JSONRequestData: %@",[[NSString alloc] initWithData:JSONRequestData encoding:NSUTF8StringEncoding]); 
[NSJSONSerialization writeJSONObject:JSONRequestData toStream:outputStream options:0 error:&error]; 

我創建的JSON對象是否錯誤?也許有一個與我處理「斑點」

這裏的方式有問題就是我創建JSONRequestData

{"security_level":"0","request_type":"send_string","device_type":"ios","blob":{"string":"hello"}} 

回答

3

writeJSONObject後NSLogs打印期待你想要的實際序列化對象發送,所以在這種情況下,你想通過它requestData對象,而不是JSONRequestData喜歡:

NSJSONSerialization writeJSONObject:requestData toStream:outputStream options:0 error:&error]; 
+0

我有一種感覺,我正在採取步驟太多。謝謝! – khaliq 2012-08-13 20:16:24

相關問題