2012-08-13 32 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

相关问题