我无法解决这个错误:
*** 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对象?也许我处理“blob”的方式存在问题
这是我创建JSONRequestData后打印的NSLogs
{"security_level":"0","request_type":"send_string","device_type":"ios","blob":{"string":"hello"}}
答案 0 :(得分:3)
writeJSONObject
期望您要发送的实际反序列化对象,因此在这种情况下,您需要将requestData
对象传递给它,而不是JSONRequestData
,如:
NSJSONSerialization writeJSONObject:requestData toStream:outputStream options:0 error:&error];