我正在尝试创建一个如下所示的 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'
最佳答案
替换这一行
0,@"security_level"
与
[NSNumber numberWithInt:0],@"security_level"
关于ios - 使用 iOS 5 创建 JSON - 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11930316/