我正在尝试创建一个如下所示的 JSON 对象:
{ "request_type":"send_string" "security_level":0 "device_type":"ios" "blob":{"string":"blah"}"}
这是我的尝试:
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",
0,@"security_level",
@"ios",@"device_type",
//No Email Provided, This is just for testing
blobString,@"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 userInfo] objectForKey:@"NSDebugDescription"]);
NSLog(@"%@",[[NSString alloc] initWithData:JSONRequestData encoding:NSUTF8StringEncoding]);
问题是,最后一个 NSLog 告诉我我创建的所有内容都是这样的:
{"request_type":"send_string"}
所以当我去尝试将其写入服务器时
[NSJSONSerialization writeJSONObject:JSONRequestData toStream:outputStream options:0 error:&error];
我从控制台收到此错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization writeJSONObject:toStream:options:error:]: Invalid top-level type in JSON write'