ios - 使用 iOS 5 创建 JSON - 问题

标签 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'

最佳答案

替换这一行

0,@"security_level"

[NSNumber numberWithInt:0],@"security_level"

关于ios - 使用 iOS 5 创建 JSON - 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11930316/

相关文章:

ios - 与 SDWebImage 相关的架构 arm64 的重复符号

Android:用gson解析raw文件夹中的JSON文件?

java - 无法从字符串值 '/Date(1458672480000)/' 构造 java.util.Date 的实例

json - 如何在不是字典的json模式中进行模式引用的嵌套列表(数组)

ios - 如何在 iOS/Swift 项目中清晰分离 ui 和业务逻辑

ios - 获取请求后的冗余 TableView

ios - UITableViewCellAccessory 多节

android - org.json.JSONObject 无法转换为 JSONArray

r - 使用 purrr 或 rlist 从 json 文件中查找元素

ios - 在 UITableViewCell 上实现选择和突出显示动画的正确方法是什么?