Reputation: 3115
I'm having trouble figuring this error out:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization writeJSONObject:toStream:options:error:]: Invalid top-level type in JSON write'
Which pertains to this chunk of code (basically I'm creating some JSON and sending it off to a server). I have already checked with the server to see if the socket is opened, which it is!
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];
Am I creating the JSON object wrong? Maybe there's a problem with the way I'm handling the "blob"
Here's what the NSLogs prints after I've created JSONRequestData
{"security_level":"0","request_type":"send_string","device_type":"ios","blob":{"string":"hello"}}
Upvotes: 4
Views: 14295
Reputation: 2759
writeJSONObject
expects the actual unserialized object you want to send, so in this case you'd want to pass it the requestData
object, not JSONRequestData
like:
NSJSONSerialization writeJSONObject:requestData toStream:outputStream options:0 error:&error];
Upvotes: 3