使用iOS 5创建JSON - 问题

时间:2012-08-13 08:07:16

标签: ios json

我正在尝试创建一个如下所示的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'

1 个答案:

答案 0 :(得分:2)

替换此行

0,@"security_level"

[NSNumber numberWithInt:0],@"security_level"